This topic describes how to build an application using the Hibernate framework and OceanBase AI Database to perform basic operations such as creating tables, inserting data, and querying data.
Prerequisites
- You have installed OceanBase AI Database.
- You have installed Java Development Kit (JDK) 1.8 and Maven.
- You have installed IntelliJ IDEA.
Note
The tool used to run the sample code in this topic is IntelliJ IDEA 2021.3.2 (Community Edition). You can also choose a tool that suits your personal preference to run the sample code.
Procedure
Note
The procedure described in this topic is based on the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Obtain the connection string for OceanBase AI Database.
- Import the
java-oceanbase-hibernateproject into IDEA. - Modify the database connection information in the
java-oceanbase-hibernateproject. - Run the
java-oceanbase-hibernateproject.
Step 1: Obtain the OceanBase AI Database connection string
Contact the deployment personnel or administrator of OceanBase AI Database to obtain the connection string.
obclient -hxx.xx.xx.xx -P2883 -uroot@sys#cluster -p**** -AEnter the URL of OceanBase AI Database.
Note
This URL information is required in the
hibernate.cfg.xmlfile.jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$passwordParameter description:
host: The IP address for connecting to OceanBase AI Database. For ODP connections, use an ODP address; for direct connections, use the IP address of an OBServer node.port: The port for connecting to OceanBase AI Database. For ODP connections, the default port is2883, which can be customized during ODP deployment. For direct connections, the default port is2881, which can be customized during OceanBase AI Database deployment.schema_name: The name of the schema to access.user_name: Specified using the-uparameter, in the format user@tenant#cluster_name or username@SERVICE:service_name. When using the user@tenant#cluster_name format, the default tenant issysand the administrator user isroot. The cluster name can be omitted when directly connecting to the database, but is required for ODP connections.password: The account password.
For more information about URL parameters, see Database URL.
Step 2: Import the java-oceanbase-hibernate project into IDEA
Start IntelliJ IDEA and choose File > Open....

In the Open File or Project window that appears, select the corresponding project file and click OK to import it.
IntelliJ IDEA automatically recognizes the various files in the project. In the Project tool window, you can view the project's directory structure, file list, module list, dependencies, and other information. The Project tool window is usually located on the far-left side of the IntelliJ IDEA interface and is open by default. If the Project tool window is closed, you can reopen it by clicking View > Tool Windows > Project in the menu bar or using the shortcut key Alt + 1.
Note
When importing a project with IntelliJ IDEA, it automatically detects the pom.xml file in the project, downloads the required dependency libraries based on the dependencies described in the file, and adds them to the project.
View the project.

Step 3: Modify the database connection information in the java-oceanbase-hibernate project
Modify the database connection information in the hibernate.cfg.xml file based on the information obtained in Step 1: Obtain the OceanBase AI Database connection string.
Note
If you need to add additional properties to the JDBC connection string, see Database URL.
Here is a connection information example:
- The name of the database driver is
com.mysql.cj.jdbc.Driver. - The IP address of the OBServer node is
172.30.xxx.xxx. - The access port is 2881.
- The name of the schema to be accessed is
test. - The tenant account is
root@mysql001.mysql001is a user tenant created in OceanBase AI Database, androotis the username of themysql001tenant. - The password is
******.
The sample code is as follows:
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://172.30.xxx.xxx:2881/test</property>
<property name="hibernate.connection.username">root@mysql001</property>
<property name="hibernate.connection.password">******</property>
Step 4: Run the java-oceanbase-hibernate project
Run path
- Locate the
TestHibernate.javafile in the src > test > java directory of the project structure. - In the tool menu bar, select Run (U) > Run > TestHibernate, or directly click the green triangle in the upper-right corner to run it.
- View the project's log information and output results through IDEA's console.
Run result
User{id=2, name='update'}
User{id=3, name='user_insert3'}
User{id=4, name='user_insert4'}
User{id=5, name='user_insert5'}
Project code
Click java-oceanbase-hibernate to download the project code, which is a compressed file named java-oceanbase-hibernate.zip.
After decompressing it, you will get a folder named java-oceanbase-hibernate. The directory structure is as follows:
│--pom.xml
│
├─.idea
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─oceanbase
│ │ │ ├─dao
│ │ │ │ └─--UserDao.java
│ │ │ │
│ │ │ └─pojo
│ │ │ └─--User.java
│ │ │
│ │ └─resources
│ │ │--hibernate.cfg.xml
│ │ │
│ │ └─com
│ │ └─oceanbase
│ │ └─pojo
│ │ └─--User.hbm.xml
│ │
│ └─test
│ └─java
│ └─--TestHibernate.java
│
└─target
The files and directories are described as follows:
pom.xml: The configuration file for the Maven project, containing information such as project dependencies, plugins, and builds..idea: A directory used by the IDE (Integrated Development Environment) to store project-related configuration information.src: Typically denotes the directory that holds the project's source code.main: The directory for storing the main source code and resource files.java: The directory for storing Java source code.com: The root directory for Java packages.oceanbase: The root directory for the project.dao: The directory for storing Data Access Object (DAO) packages, used to access databases or other data storage services.UserDao.java: The user data access object, used for operations such as adding, deleting, modifying, and querying user data.User.java: The user persistence object, used to map fields of the user data table.pojo: Plain Old Java Objects (POJOs), storing Java classes corresponding to database tables. Used to map database tables or other data storage structures.resources: The directory for storing resource files, such as configuration files and SQL files.hibernate.cfg.xml: The configuration file for Hibernate, used to configure basic parameters and set data sources.User.hbm.xml: The mapping file for the user persistence object, used to define the mapping relationship between the user persistence object and the user data table.test: The directory for storing test code and resource files.TestHibernate.java: The Java class for testing Hibernate.target: The directory for storing compiled Class files, JAR packages, and other files.
Code in pom.xml
Note
If you just want to verify the example, use the default code without modification. You can also modify the pom.xml file according to your needs as described below.
The content of the pom.xml configuration file is as follows:
The document declaration statement.
Declares that this file is an XML file, using XML version
1.0and character encodingUTF-8.The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
xmlns: the default XML namespace for the POM, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the XML namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the location of an XML schema definition (XSD) file. The value consists of two parts: the default XML namespace (http://maven.apache.org/POM/4.0.0) and the URI of the XSD file (http://maven.apache.org/xsd/maven-4.0.0.xsd).<modelVersion>: the POM model version used by the POM file, which is set to4.0.0.
The sample code is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> </project>Configure basic information.
- Use
<groupId>to specify the project identifier ascom.oceanbase. - Use
<artifactId>to specify the project dependency asjava-oceanbase-hibernate. - Use
<version>to specify the project version as1.0-SNAPSHOT.
The sample code is as follows:
<groupId>com.oceanbase</groupId> <artifactId>java-oceanbase-hibernate</artifactId> <version>1.0-SNAPSHOT</version>- Use
Define the project build process using
<build>.- Use
<plugins>to specify the plugins configured in the project. - Use
<plugin>to specify a plugin to configure in the project. - Use
<groupId>to specify the project identifier asorg.apache.maven.plugins. - Use
<artifactId>to specify the project dependency asmaven-compiler-plugin. - Use
<configuration>to specify the parameters for the configured plugin. - Use
<source>to specify the compiler's source code version as 8. - Use
<target>to specify the compiler's target code version as 8.
The sample code is as follows:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>- Use
Define the components on which the project depends using
<dependencies>.Specify the dependency's organization as
com.oceanbase, name asoceanbase-client, and version as2.4.2.The sample code is as follows:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>Specify the dependency's test framework as
junit, name asjunit, and version as4.13.The sample code is as follows:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> </dependencies>Specify the dependency's framework as
org.hibernate, core library ashibernate-core, and version as5.2.17.Final.The sample code is as follows:
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.17.Final</version> </dependency> </dependencies>Specify the dependency's framework as
org.hibernate, data source library ashibernate-c3p0, and version as5.2.17.Final.The sample code is as follows:
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>5.2.17.Final</version> </dependency> </dependencies>
Code in User.hbm.xml
The User.hbm.xml file is a Hibernate mapping file that maps Java objects to tables in the database.
The code in the User.hbm.xml file mainly consists of the following parts:
File declaration statement.
Declares this file as an XML file, using XML version
1.0and character encodingUTF-8. It also specifies the DTD version and location for the Hibernate mapping file, setting the DTD document type tohibernate-mapping, version 3.0, language EN, and the file URL to `http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd``The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">Configuration of the mapping file.
Defines a Hibernate mapping file that maps the entity class named
Userto a database table namedtest_hibernate_mysql.- Uses the
packageattribute to specify the Java package in the mapping file ascom.oceanbase.pojo. - Uses the
classtag to map data from the database table. Thenameattribute specifies the Java class name asUser, and thetableattribute specifies the database table name astest_hibernate_mysql. - Defines the primary key attribute using
id. Thenameattribute specifies the member variableidof the Java classUser, and thecolumnattribute specifies the database field name asUSER_ID. - Defines the primary key generation strategy using
generator. Theclassattribute specifies the primary key generator type assequence. Theparamelement specifies the sequence name in the database asSQ_USER. Thenameattribute specifies this attribute corresponds to theUSER_NAMEcolumn in the database table and sets its data type to string.
The sample code is as follows:
<hibernate-mapping package="com.oceanbase.pojo"> <class name="User" table="test_hibernate_mysql"> <!-- Configure primary key generation strategy --> <id name="id" column="USER_ID"> <generator class="sequence"> <param name="sequence">SQ_USER</param> </generator> </id> <!-- Configuration Tables and Properties --> <property name="name" column="USER_NAME" type="string"/> </class> </hibernate-mapping>- Uses the
Code in hibernate.cfg.xml
The hibernate.cfg.xml file is a configuration file for Hibernate, used to configure the runtime environment of Hibernate and the parameters for connecting to a database.
The code in the hibernate.cfg.xml file mainly includes the following parts:
The file declaration statement.
Declares that this file is an XML file, using XML version
1.0and character encodingUTF-8. It also specifies the DTD version and location for the Hibernate configuration file, setting the DTD document type tohibernate-configuration, version 3.0, language EN, and the file URL as `http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd``The sample code is as follows:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">Configure the
configurationparameters.In the
<hibernate-configuration>root element, the<session-factory>element is used to set up Hibernate's session factory, which is responsible for creating and managing session objects. The session factory includes configurations such as the driver class name for connecting to the database, URL, username and password, connection pool parameters, database dialect, SQL output and formatting, automatic creation of database tables, current session context, batch processing, and secondary caching.Configure database information.
Configure the parameters for Hibernate to connect to the database, including the driver class name, URL, username, and password for connecting to the database.
- Use
hibernate.connection.driver_classto specify the database driver ascom.mysql.cj.jdbc.Driver, used to establish a connection with OceanBase AI Database. - Use the
hibernate.connection.urlelement to specify the database URL, including the database address, port number, and database name. - Use the
hibernate.connection.usernameelement to specify the username for connecting to the database. - Use the
hibernate.connection.passwordelement to specify the password for connecting to the database.
The sample code is as follows:
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:oceanbase://host:port/schema_name</property> <property name="hibernate.connection.username">user_name</property> <property name="hibernate.connection.password">******</property>- Use
Configure connection pool information.
Configure the relevant parameters for the connection pool used by Hibernate. Specify the connection pool as C3P0. Parameter settings include the maximum and minimum number of connections in the pool, timeout period, maximum idle time for a connection, number of cached Statement objects, idle test period for a connection, number of connections acquired at once, and connection validation method.
Note
The following parameters are for reference only and do not represent a complete list of supported parameters. To configure other parameters, refer to the relevant documentation for more detailed parameter information.
- Use
hibernate.connection.provider_classto specify the connection pool as C3P0, which manages the creation and release of database connections. - Use
hibernate.c3p0.max_sizeto specify the maximum number of connections in the pool as 60. - Use
hibernate.c3p0.min_sizeto specify the minimum number of connections in the pool as 30. - Use
hibernate.c3p0.checkoutTimeoutto specify the timeout period for acquiring a connection from the pool as 30000 milliseconds. - Use
hibernate.c3p0.timeoutto specify the maximum idle time for a connection as 2000 milliseconds; connections exceeding this time will be closed. - Use
hibernate.c3p0.max_statementsto specify the maximum number of SQL statements cached in the pool as 100. - Use
hibernate.c3p0.idle_test_periodto specify the detection cycle for idle connections in the pool as 3000 milliseconds. - Use
hibernate.c3p0.acquire_incrementto specify the increment by which the number of connections grows dynamically in the pool as 3. - Use
hibernate.c3p0.validateto specify connection validation as true when connecting to the pool.
The sample code is as follows:
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.max_size">60</property> <property name="hibernate.c3p0.min_size">30</property> <property name="hibernate.c3p0.checkoutTimeout">30000</property> <property name="hibernate.c3p0.timeout">20000</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">3</property> <property name="hibernate.c3p0.validate">true</property>- Use
Configure SQL interaction information. Configure information related to the connection between Hibernate and the database. This includes the database dialect, SQL printing and formatting, automatic table creation, the current session context, batch processing size, cache usage, and the loading of mapping files.
- Use
dialectto specify the database dialect as MySQL 5.7 to ensure compatibility with a specific database. - Use
hibernate.show_sqlto set whether to print SQL statements generated by Hibernate to the console. - Use
hibernate.format_sqlto set whether to format printed SQL statements. - Use
hbm2ddl.autoto set automatic table creation. - Use
current_session_context_classto specify the use of a thread-level current session context. - Use
hibernate.jdbc.batch_sizeto set the batch processing size. - Use
hibernate.cache.use_second_level_cacheto set whether to enable the second-level cache. - Specify to load the mapping file
com/oceanbase/pojo/User.hbm.xml.
The sample code is as follows:
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hbm2ddl.auto">create</property> <property name="current_session_context_class">thread</property> <property name="hibernate.jdbc.batch_size">10</property> <property name="hibernate.cache.use_second_level_cache">false</property> <mapping resource="com/oceanbase/pojo/User.hbm.xml"/>- Use
Code in UserDao.java
The UserDao.java file implements user data CRUD operations using a Session object through the User Data Access Object (DAO) class.
The code in the UserDao.java file mainly consists of the following parts:
References to other classes and interfaces.
Declares that this file contains the following interfaces and classes:
Userclass: used to manipulate user objects.Sessionclass: used to interact with the database.SessionFactoryclass: used to create Session instances.Transactionclass: used to manage database transactions.Configurationclass: used to load the Hibernate configuration file.Queryclass: used to execute query operations.Listinterface: used to manipulate query result sets.
The sample code is as follows:
import com.oceanbase.pojo.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.util.List;Definition of the
UserDaoclass.
The UserDao Java class serves as a data access object for persisting user objects. It encapsulates a series of methods related to database interaction, performing CRUD operations on user objects. By calling the methods in the UserDao class, you can conveniently interact with the database and implement persistent operations.
Initialization of a
UserDaoclass instance.Uses an object initialization block to initialize a
Sessionobject during the class instantiation process.First, create a
Configurationobject and call itsconfiguremethod to read the Hibernate configuration file (hibernate.cfg.xml). Then, create aSessionFactoryobject by calling thebuildSessionFactorymethod. Finally, create aSessionobject by calling theopenSessionmethod and assign it to thesessionvariable.The sample code is as follows:
private Session session; { Configuration cfg = new Configuration().configure(); // Create SessionFactory SessionFactory sessionFactory = cfg.buildSessionFactory(); session = sessionFactory.openSession(); } //Read the hibernate.cfg.xml fileQuerying corresponding user information by ID.
Uses the
selectUserByIdmethod to query corresponding user information based on the provided ID parameter.Uses the
getmethod ofsession. By passing inUser.classand theIDparameter, it retrieves the User record with the corresponding ID from the database and stores it in theuservariable.The sample code is as follows:
public User selectUserById(int ID) { User user = session.get(User.class, ID); return user; }Querying user information by username.
Uses the
selectUserbyNamemethod to query user information by username. First, defines an HQL (Hibernate Query Language) statement to query user data with a specified name. The table name istest_hibernate_mysql, the table alias isu, and the query field name isname. Creates aQueryobject using thecreateQuerymethod of theSessionobject, passing the HQL statement and the entity class as parameters. Sets query parameters using thesetParametermethod of theQueryobject, where0indicates the parameter position andnameindicates the parameter value. Executes the query using thelistmethod of theQueryobject and converts the query results into a list ofUserobjects.The sample code is as follows:
public List<User> selectUserbyName(String name) { String sql = "FROM test_hibernate_mysql u WHERE u.name =?"; Query<User> query = session.createQuery(sql, User.class); query.setParameter(0, name); List<User> users = query.list(); return users; }Query all user data.
The
selectUsermethod is used to query all user data. Define an SQL statement to query all user data. Use thecreateNativeQuerymethod of theSessionobject to create aQueryobject and pass the SQL statement as a parameter. Then, use theaddEntitymethod to add the entity classUserto the query so that the query result can be converted into a list ofUserobjects. Execute the query using thegetResultListmethod of theQueryobject and convert the query result into a list of User objects.The sample code is as follows:
public List<User> selectUser() { String sql = "SELECT * FROM test_hibernate_mysql"; Query<User> query = session.createNativeQuery(sql).addEntity(User.class); List<User> users = query.getResultList(); return users; }Insert user data.
The
insertUsermethod is used to insert user information. Specify a parameteruserof typeUserto pass in the user object to be inserted. Create a transaction object by calling thebeginTransactionmethod of the Hibernate Session and save it in the variablebeginTransaction. Use thesavemethod to save the user object to the database. Get the current transaction by calling thegetTransactionmethod of theSessionand call thecommitmethod to commit the transaction, persisting the previous operations to the database and returning the result of the insertion operation.The sample code is as follows:
public int insertUser(User user) { // open transaction Transaction beginTransaction = session.beginTransaction(); session.save(user); session.getTransaction().commit(); return 1; }Delete user data.
The
deleteUserByIdmethod is used to delete the user record corresponding to the passed ID from the database. Specify an integer parameteridto pass in the ID of the user to be deleted. Start a new transaction by calling thebeginTransactionmethod of the Hibernate Session. Use thegetmethod to obtain the corresponding user object based on the specified userIDand entity class type (User.class). Use thedeletemethod to delete the user object. Get the current transaction by calling thegetTransactionmethod of theSessionand call thecommitmethod to commit the transaction, persisting the deleted user information to the database and returning the result of the deletion operation.The sample code is as follows:
public int deleteUserById(int id) { // open transaction session.beginTransaction(); User user = session.get(User.class, id); session.delete(user); session.getTransaction().commit(); return 1; }Modify user data.
The
updateUserByIdmethod is used to update the corresponding user information. Specify a parameteruserof typeUserto specify the user data to be updated. Use thebeginTransactionmethod of the Session object to start a transaction. Use thegetmethod of theSessionobject to obtain the correspondingUserobject based on the user ID. Use themergemethod of theSessionobject to merge the passedUserobject with the obtainedUserobject, updating the passed user data to the database. Get the current transaction by calling thegetTransactionmethod of theSessionobject and call thecommitmethod to commit the transaction, returning the result of the modification operation.The sample code is as follows:
public int updateUserById(User user) { // open transaction session.beginTransaction(); User user1 = session.get(User.class, user.getId()); session.merge(user); session.getTransaction().commit(); return 1; }
Code in User.java
The User.java file implements CRUD operations for user data through a Data Access Object (DAO) class and a Session object.
The code in the User.java file mainly includes the following parts:
References to other classes.
Declare that this file uses JPA annotations to configure the mapping between related classes and database tables:
Columnannotation: Identifies the correspondence between an attribute in the entity class and a column in the database table.Entityannotation: Maps to a table in the database.GeneratedValueannotation: Indicates that the value of the attribute is automatically generated.GenerationTypeannotation: Specifies the primary key generation strategy.Idannotation: Specifies the unique identifier attribute.Tableannotation: Indicates the table name corresponding to the entity class.
The sample code is as follows:
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;Map a table in the database.
Define an entity class that maps to a database table, and specify the table name corresponding to the entity class as
test_hibernate_mysql.The sample code is as follows:
@Entity @Table(name = "test_hibernate_mysql")Define the
Userclass.Use it to map to a table named
test_hibernate_mysqlin the database.Define two attributes
idandname. Use annotations to identify the correspondence between theidandnameattributes in theUserclass and the columns in the database table. Use the@Idannotation to identify theidattribute as the primary key. Use the@GeneratedValueannotation to specify the sequence as the primary key generation strategy. Use the@Columnannotation to specify the mapping between the attribute and the column in the database table. Theidattribute stores the user ID, and thenameattribute stores the username.The sample code is as follows:
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "user_id") private int id; @Column(name = "user_name") private String name;Create a
Userobject.Define two constructors for the
Userclass to createUserobjects. Define a no-argument constructor for Hibernate query operations. Define a parameterized constructor to initialize theidandnameattributes.The sample code is as follows:
public User() { } public User(int id, String name) { this.id = id; this.name = name; }Get and set the values of
idandname.Define four methods in the
Userclass to get and set the values of theidandnameattributes. ThegetIdmethod retrieves theidvalue, and thesetIdmethod sets theidvalue. ThegetNamemethod retrieves the value of the usernamename. ThesetNamemethod sets the value of the usernamename.The sample code is as follows:
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }Return a string representation of the
Userobject.Override the
toStringmethod in theUserclass to return a string representation of theUserobject. Define@Overrideto override the method with the same name in the parent class. Define thetoStringmethod to return a string representation of theUserobject. Format the values of theidandnameattributes into a string using string concatenation, and return it to the callingUser.The sample code is as follows:
@Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; }
Code in TestHibernate.java
The TestHibernate.java file demonstrates the basic database operation features of Hibernate by performing insert, delete, update, and query operations on UserDao objects.
The code in the TestHibernate.java file mainly includes the following parts:
References to other classes and interfaces.
Declare the classes and interfaces related to this file, including
UserDao,User,Session,SessionFactory,Configuration, etc.UserDaoclass: used to perform database operations related to users.Userclass: used to manipulate user objects.Sessionclass: used for session operations with the database.SessionFactoryclass: used to create Session objects.Configurationclass: used to configure Hibernate.SessionImplclass: used to obtain the underlying JDBC connection.Testannotation: used to mark test methods.IOExceptionclass: used to handle I/O exceptions.Connectionclass: used to obtain a JDBC connection.SQLExceptionclass: used to handle SQL exceptions.Listclass: used to store query result sets.UUIDclass: used to generate unique identifiers.
The sample code is as follows:
import com.oceanbase.dao.UserDao; import com.oceanbase.pojo.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.internal.SessionImpl; import org.junit.Test; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.UUID;Define the
testHibernatemethod. ThetestHibernatemethod includes basic operations such as insert, delete, update, and query. Create aUserDaoobject and insert five user records in a loop. Call theinsertUsermethod to insert user data. Call thedeleteUserByIdmethod to delete the user with id 1. Call theupdateUserByIdmethod to update the user with id 2. Call theselectUsermethod to query all user data. Traverse the query results and print them to the console.The sample code is as follows:
public class TestHibernate { @Test public void testHibernate() throws SQLException, IOException { UserDao userDao = new UserDao(); for (int i = 1; i <= 5; i++) { userDao.insertUser(new User(i, "user_insert" + i)); } int deleteUserById = userDao.deleteUserById(1); int update = userDao.updateUserById(new User(2, "update")); List<User> users = userDao.selectUser(); users.forEach(System.out::println); } }
Complete code examples
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oceanbase</groupId>
<artifactId>java-oceanbase-hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<!-- Hibernate c3p0 connection pool-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.17.Final</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.oceanbase.pojo">
<class name="User" table="test_hibernate_mysql">
<!-- Configure primary key generation strategy -->
<id name="id" column="USER_ID">
<generator class="sequence">
<param name="sequence">SQ_USER</param>
</generator>
</id>
<!-- Configuration Tables and Properties -->
<property name="name" column="USER_NAME" type="string"/>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://host:port/schema_name</property>
<property name="hibernate.connection.username">user_name</property>
<property name="hibernate.connection.password">******</property>
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">60</property>
<property name="hibernate.c3p0.min_size">30</property>
<property name="hibernate.c3p0.checkoutTimeout">30000</property>
<property name="hibernate.c3p0.timeout">20000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">3</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.jdbc.batch_size">10</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<mapping resource="com/oceanbase/pojo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.oceanbase.dao;
import com.oceanbase.pojo.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.util.List;
public class UserDao {
private Session session;
{
Configuration cfg = new Configuration().configure();
// Create SessionFactory
SessionFactory sessionFactory = cfg.buildSessionFactory();
session = sessionFactory.openSession();
} //Read the hibernate.cfg.xml file
// private Session session = HibernateUtil.getSession();
public User selectUserById(int ID) {
User user = session.get(User.class, ID);
return user;
}
public List<User> selectUserbyName(String name) {
String sql = "FROM test_hibernate_mysql u WHERE u.name =?";
Query<User> query = session.createQuery(sql, User.class);
query.setParameter(0, name);
List<User> users = query.list();
return users;
}
public List<User> selectUser() {
String sql = "SELECT * FROM test_hibernate_mysql";
Query<User> query = session.createNativeQuery(sql).addEntity(User.class);
List<User> users = query.getResultList();
return users;
}
public int insertUser(User user) {
// open transaction
Transaction beginTransaction = session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return 1;
}
public int deleteUserById(int id) {
// open transaction
session.beginTransaction();
User user = session.get(User.class, id);
session.delete(user);
session.getTransaction().commit();
return 1;
}
public int updateUserById(User user) {
// open transaction
session.beginTransaction();
User user1 = session.get(User.class, user.getId());
session.merge(user);
session.getTransaction().commit();
return 1;
}
}
package com.oceanbase.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "test_hibernate_mysql")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "user_id")
private int id;
@Column(name = "user_name")
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
import com.oceanbase.dao.UserDao;
import com.oceanbase.pojo.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.internal.SessionImpl;
import org.junit.Test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
public class TestHibernate {
@Test
public void testHibernate() throws SQLException, IOException {
UserDao userDao = new UserDao();
for (int i = 1; i <= 5; i++) {
userDao.insertUser(new User(i, "user_insert" + i));
}
int deleteUserById = userDao.deleteUserById(1);
int update = userDao.updateUserById(new User(2, "update"));
List<User> users = userDao.selectUser();
users.forEach(System.out::println);
}
}
References
For more information about OceanBase Connector/J, see OceanBase JDBC driver
Download the java-oceanbase-hibernate sample project