JOOQ Simple CRUD operation example

Environment Used

Java 1.7

JOOQ 3.2

Eclipse

MySql

1. What is JOOQ?

Java Object Oriented Querying is a light weight database mapping API in java that implements the active record pattern. The main objective of this API to provide domain specific language to construct queries and generating classes from database schema. See more about jooq

2. Setup JOOQ Project

Create a java project and add below jars in the class path (Click here to download jars)

image

3. Generate Code

jOOQ generates Java code from your database and lets you build typesafe SQL queries through its fluent API. See this example to Generate Jooq code

4. Create a java class to create connection

package com.pretech.utility;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcConnection {
	
	public static Connection getConnection()
	{Connection conn = null;
	String userName = "root";
	String password = "root";
	String url = "jdbc:mysql://localhost:3306/studentdatabase";
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, userName, password);
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
}

5. Create a main class for CRUD operation

package com.pretech.master;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.types.UInteger;
import com.pretech.jooq.tables.Student;
import com.pretech.jooq.tables.records.StudentRecord;
import com.pretech.utility.JdbcConnection;
public class StudentMaster {
	public static void main(String[] args) {
		try {
			DSLContext create = DSL.using(JdbcConnection.getConnection(),
					SQLDialect.MYSQL);
			// INSERTING STUDENT DETAILS
			create.insertInto(Student.STUDENT, Student.STUDENT.ID,
					Student.STUDENT.NAME, Student.STUDENT.STANDARD)
					.values(UInteger.valueOf(1), "Rajesh", "10th Standard")
					.execute();
			System.out.println("STUDENT RECORDS AFTER INSERTING");
			// SELECTING STUDENT RECORDS
			Result<Record> result0 = create.select().from(Student.STUDENT)
					.fetch();
			for (Record r : result0) {
				StudentRecord stud = (StudentRecord) r;
				System.out.println(stud);
			}
			create.update(Student.STUDENT)
					.set(Student.STUDENT.STANDARD, "9th standard")
					.where(Student.STUDENT.ID.equal(UInteger.valueOf(1))).execute();
			System.out.println("STUDENT RECORDS AFTER UPDATING");
			// SELECTING STUDENT RECORDS
			Result<Record> result1 = create.select().from(Student.STUDENT)
					.fetch();
			for (Record r : result1) {
				StudentRecord stud = (StudentRecord) r;
				System.out.println(stud);
			}
			create.delete(Student.STUDENT).execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

6. Final structure of the project


image


7. Output



image



8. Download this example


Download JOOQ Simple CRUD operation example

How to generate jOOQ code using eclipse ?

jOOQ generates Java code from your database and lets you build typesafe SQL queries through its fluent API. In this example we will see how to generate code using eclipse and MySql

1. Create a Java project and add below jars in the class path

1. jooq-xxxx.jar –This is the core library for jOOQ

2. jooq-meta-xxxx.jar- This jar includes utility class to navigate database schema for code generation

3. jooq-codegen-xxxx.jar- Utility to generate code for database schema

All these jars are available in http://www.jooq.org/download/

4. Java mysql connector jar- Available in http://www.mysql.com/products/connector/

2. Create a database schema and table in MySql database

                     image

3. Create below xml under project src folder (student.xml)

In this xml file we need to mention database connection and schema details to generate code

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.2.0.xsd">
  <jdbc>
    <driver>com.mysql.jdbc.Driver</driver>
    <url>jdbc:mysql://localhost:3306/studentdatabase</url>
    <user>root</user>
    <password>root</password>
  </jdbc>
  <generator>
    <name>org.jooq.util.DefaultGenerator</name>
    <database>
      <name>org.jooq.util.mysql.MySQLDatabase</name>
      <inputSchema>studentdatabase</inputSchema>
      <excludes></excludes>
    </database>
    <target>
      <packageName>com.pretech.jooq</packageName>
      <directory>D:\Projects\stsworkspace\JooqStudentExample\src</directory>
    </target>
  </generator>
</configuration>

4. Eclipse run configuration


Right click on the project and select ‘Run As’ Run configuration and Select main class org.jooq.util.GenerationTool


image l


Argument parameter should be the xml file which we created in step 3


image


5. Run it

Run the org.jooq.util.GenerationTool and we can see the codes are generated in the target directory which we mentioned in the student.xml file
Final structure of the project
image

What are the Jars required for jOOQ code generation?

Below are the jars required for JOOQ based ORMing and code generation.

1. jooq-xxxx.jar –This is the core library for jOOQ

2. jooq-meta-xxxx.jar- This jar includes utility class to navigate database schema for code generation

3. jooq-codegen-xxxx.jar- Utility to generate code for database schema

4. JDBC driver jars

First three jars are available in http://www.jooq.org/download/

Spring JmsTemplate and MessageListener Example

Spring provides a JMS integration framework that simplifies the use of the JMS API, the JmsTemplate class is the core class which is available in spring JMS package. This class simplifies sending and receiving messages via simple spring configuration. In this example we will see how to send and listen a message using spring JmsTemplate and Apache activemq.

Environment Used

Java 1.7
Spring-jms 3.1.2
Activemq 5.8.0
Maven

Prerequisite

Start ActiveMQ message broker.

1. Create a Maven project and add below dependencies

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>

2. Create Spring configuration file (applicationContext.xml)

Configure Activmq ,JMS Message listener and jms template beans here

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context.xsd
                          http://www.springframework.org/schema/jms
                          http://www.springframework.org/schema/jms/spring-jms.xsd
                          http://activemq.apache.org/schema/core
                          http://activemq.apache.org/schema/core/activemq-core.xsd">

 
    <context:component-scan base-package="com.pretech" />
    <context:annotation-config />
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>
 
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="myMessageQueue" />
    </bean>
    <jms:listener-container connection-factory="connectionFactory">
        <jms:listener destination="myMessageQueue" ref="messageListenerExample" />
    </jms:listener-container>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destination" />
    </bean>
 
</beans>

3. Create a Listener class to implements MessageListener

package com.pretech;
 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
 
import org.springframework.stereotype.Component;
 
@Component("messageListenerExample")
public class MessageListenerExample implements MessageListener {
 
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            ObjectMessage msg = (ObjectMessage)message;
          try {
            System.out.println("OnMessage Received :"+msg.getObject().toString());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }}
}
 
}

4. Create a Main class to send messages (MessageSender.java)

package com.pretech;
 
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Session;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
 
public class MessageSender {
    public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          JmsTemplate jmsTemplate=(JmsTemplate) context.getBean("jmsTemplate");
          jmsTemplate.send(
                new MessageCreator() {
                      public ObjectMessage  createMessage(Session session) throws JMSException {
                          ObjectMessage message = session.createObjectMessage();
                          message.setObject("My first Message");                      
                           return message;
                      }
        }  );
 
          System.out.println("MESSAGE SENT TO myMessageQueue");
    }
 
}

5. Run it

Run the MessageSender.java and we will see below output in the console 

OnMessage Received  :My first Message
MESSAGE SENT TO myMessageQueue

Reference

Spring JMS

Spring JmsTemplate Send and Receive Example

Spring provides a JMS integration framework that simplifies the use of the JMS API, the JmsTemplate class is the core class which is available in spring JMS package. This class simplifies sending and receiving messages via simple spring configuration. In this example we will see how to send and receive a message to message broker using spring JmsTemplate and Apache activemq.

Environment Used

Java 1.7
Spring-jms 3.1.2
Activemq 5.8.0
Maven

Prerequisite

Start ActiveMQ message broker.

1. Create a Maven project and add below dependencies

 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
2. Create Spring configuration file (applicationContext.xml)
Configure Activmq and jms template beans here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context.xsd
                          http://www.springframework.org/schema/jms
                          http://www.springframework.org/schema/jms/spring-jms.xsd
                          http://activemq.apache.org/schema/core
                          http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <value>tcp://localhost:61616</value>
        </property>
    </bean>

    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="myMessageQueue" />
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="destination" />
    </bean>

</beans>
 

3. Create a Main class to send and receive messages (MessageReceiver.java)

package com.pretech;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class MessageReceiver {

    public static void main(String[] args) throws JMSException {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          JmsTemplate jmsTemplate=(JmsTemplate) context.getBean("jmsTemplate");
          jmsTemplate.send(
                new MessageCreator() {
                      public ObjectMessage  createMessage(Session session) throws JMSException {
                          ObjectMessage message = session.createObjectMessage();
                          message.setObject("My first Message");                    
                           return message;
                      }
        }  );
     
          System.out.println("MESSAGE SENT TO myMessageQueue");
          Message receivedMessage=jmsTemplate.receive("myMessageQueue");
          ObjectMessage msg = (ObjectMessage)receivedMessage;
          System.out.println("Message Received :"+msg.getObject().toString());
    }

}
4. Run it

Run the MessageSender.java and we will see below output in the console and Active MQ broker

MESSAGE SENT TO myMessageQueue
Message Received :My first Message
image

Reference

Spring JMS

Spring HibernateTemplate Example

HibernateTemplate class is a Helper class that simplifies Hibernate data access code. Here is one simple example to save student details in to mysql database.

Spring Formatter Example

Spring Formatter interface has many implementations, in this example we will see how to format Currency and Date using Spring formatter.

Example

package com.pretech;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import org.springframework.format.Formatter;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.number.CurrencyFormatter;
public class SpringFormatterExample {
	public static void main(String[] args) throws ParseException {
		// Currency Formatter
		Formatter<Number> currencyFormatter = new CurrencyFormatter();
		System.out.println(currencyFormatter.print(12, Locale.US));
		// Date Formatter
		Formatter<Date> datetformatter = new DateFormatter();
		System.out.println(datetformatter.print(new Date(), Locale.CHINA));
		System.out.println(datetformatter.print(new Date(), Locale.JAPANESE));
	}
}

Output



$12.00
2013-12-13
2013/12/13


Spring Type Converter Example

Spring GenericConversionService provides method to convert one data type to another data type, here is one to convert String to Integer and String to List.

Example

package com.pretech;
import java.io.IOException;
import java.util.List;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.GenericConversionService;
public class SpringTypeConverterExample {
	public static void main(String[] args) throws IOException {
		
		GenericConversionService springconversionService = ConversionServiceFactory.createDefaultConversionService();
		//Integer to String
		
		String str = springconversionService.convert(222,String.class);
		System.out.println(str);
		
		//String to Integer
		
		Integer integer = springconversionService.convert("100",Integer.class);
		System.out.println(integer);
		
		//Comma separated String to List
		List<String> list = springconversionService.convert("sunday,monday,tuesday",List.class);
		for(String st: list){
			System.out.println("List values :"+st);
		}
		
	}
}

Output



222
100
List values :sunday
List values :monday
List values :tuesday


Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts