This topic describes how to build an application using the Hibernate framework and OceanBase Cloud to perform basic operations such as creating tables, inserting data, and querying data.
Prerequisites
- You have registered an OceanBase Cloud account and created a cluster instance and an OceanBase Cloud tenant in Oracle-compatible mode. For more information, see Create a cluster instance and Create a tenant.
- You have installed 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 the OceanBase Cloud database.
- Import the
java-oceanbase-hibernateproject into IntelliJ IDEA. - Modify the database connection information in the
java-oceanbase-hibernateproject. - Run the
java-oceanbase-hibernateproject.
Step 1: Obtain the OceanBase Cloud database connection string
Log in to the OceanBase Cloud console. On the instance list page, expand the target instance's information, and under the target tenant, select Connect > Get connection string.
For more detailed operations, see Obtain a connection string.
Fill in the corresponding information in the URL below based on your created OceanBase Cloud 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 connection address of the OceanBase Cloud database, for example,t********.********.oceanbase.cloud.$port: The connection port of the OceanBase Cloud database. The default is 1521.$schema_name: The name of the schema to access.$user_name: The account for accessing the database.$password: The password for the account.
For more information about URL parameters, see Database URL.
Step 2: Import the java-oceanbase-hibernate project into IntelliJ IDEA
Open IntelliJ IDEA and select 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 Cloud connection string.
Note
To add additional properties to the JDBC connection string, see Database URL.
Example:
- The database driver name is:
com.oceanbase.jdbc.Driver - The OceanBase Cloud connection address is
t5******.********.oceanbase.cloud. - The access port is 1521.
- The schema name to access is
sys. - The tenant connection account is oracle001.
- The password is
******.
Sample code:
<property name="hibernate.connection.driver_class">com.oceanbase.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:oceanbase://t5******.********.oceanbase.cloud:1521/sys</property>
<property name="hibernate.connection.username">oracle001</property>
<property name="hibernate.connection.password">******</property>
Step 4: Run the java-oceanbase-hibernate project
Run the application
- 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.
Output
User{id=2, name='update'}
User{id=3, name='user_insert3'}
User{id=4, name='user_insert4'}
User{id=5, name='user_insert5'}
Sample project overview
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
File description:
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 primary 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 creating, reading, updating, and deleting user data.User.java: The user persistence object, used to map fields from the user data table.pojo: Plain Old Java Objects (POJOs), containing 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 up data sources.User.hbm.xml: The mapping file for the user persistence object, used to define the mapping 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.
Introduction to pom.xml code
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 file declaration statement.
Declares that this file is an XML file, using XML version
1.0and character encodingUTF-8.Code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM namespace and POM model version.
- Use
xmlnsto specify the POM namespace ashttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito specify the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto specify the POM namespace,http://maven.apache.org/POM/4.0.0, and the location of its XSD file,http://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to specify the POM model version used by this POM file as4.0.0.
Code:
<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>- Use
Configure basic information.
- Use
<groupId>to set the group ID tocom.oceanbase. - Use
<artifactId>to set the artifact ID tojava-oceanbase-hibernate. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Code:
<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 set the group ID toorg.apache.maven.plugins. - Use
<artifactId>to set the artifact ID tomaven-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.
Code:
<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 through
<dependencies>.Specify that the dependency belongs to the organization
com.oceanbase, its name isoceanbase-client, and its version is2.4.2.Sample code:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>Specify that the dependency belongs to the testing framework
junit, its name isjunit, and its version is4.13.Sample code:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> </dependencies>Specify that the dependency belongs to the framework
org.hibernate, its core library ishibernate-core, and its version is5.2.17.Final.Sample code:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.17.Final</version> </dependency> </dependencies>Specify that the dependency belongs to the framework
org.hibernate, its data source library ishibernate-c3p0, and its version is5.2.17.Final.Sample code:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>hibernate-c3p0</artifactId> <version>5.2.17.Final</version> </dependency> </dependencies>
Introduction to User.hbm.xml
The User.hbm.xml file is a Hibernate mapping file used to map Java objects to tables in the database.
The code in the User.hbm.xml file mainly consists of 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 mapping file, setting the DTD document type tohibernate-mapping, version 3.0, language EN, and the file URL tohttp://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd.Sample code:
<?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 to map the entity class named
Userto a database table namedtest_hibernate_oracle.- Uses the
packageattribute to specify the Java package in the mapping file ascom.oceanbase.pojo. - Uses the
classtag to map data from the table. Thenameattribute specifies the Java class name asUser, and thetableattribute specifies the database table name astest_hibernate_oracle. - 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 that this attribute corresponds to theUSER_NAMEcolumn in the database table, and sets its data type to string.
Sample code:
<hibernate-mapping package="com.oceanbase.pojo"> <class name="User" table="test_hibernate_oracle"> <id name="id" column="USER_ID"> <generator class="sequence"> <param name="sequence">SQ_USER</param> </generator> </id> <property name="name" column="USER_NAME" type="string"/> </class> </hibernate-mapping>- Uses the
Introduction to 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:
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 ashttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.Code:
<?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 second-level 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.oceanbase.jdbc.Driver, used to establish a connection with OceanBase Cloud. - 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.
Code:
<property name="hibernate.connection.driver_class">com.oceanbase.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. If you need 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 the connection validation method as true.
Sample code:
<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 the 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 loading of mapping files.
- Use
dialectto specify the database dialect as Oracle 12c 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.
Sample code:
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</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
Introduction to UserDao.java
The UserDao.java file uses a User Data Access Object (DAO) class to implement create, read, update, and delete operations for user data through a Session object.
The code in the UserDao.java file mainly includes 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.Sessioninterface: used to interact with the database.SessionFactoryinterface: used to create aSessioninstance.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.
Code:
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 operations such as creating, reading, updating, and deleting user objects. By calling the methods in the UserDao class, you can easily interact with the database and perform 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, call thebuildSessionFactorymethod to create aSessionFactoryobject. Finally, call theopenSessionmethod to create aSessionobject and assign it to thesessionvariable.Code:
private Session session; { Configuration cfg = new Configuration().configure(); // Create SessionFactory SessionFactory sessionFactory = cfg.buildSessionFactory(); session = sessionFactory.openSession(); } //Read the hibernate.cfg.xml fileQuerying user information by ID.
The
selectUserByIdmethod is used to query user information by providing an ID parameter.Uses the
sessionobject'sgetmethod to retrieve the User record with the specified ID from the database based on the passedUser.classandIDparameters, and stores it in theuservariable.Code:
public User selectUserById(int ID) { User user = session.get(User.class, ID); return user; }Querying user information by username.
The
selectUserbyNamemethod is used 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_oracle, the table alias isu, and the query field name isname. Uses theSessionobject'screateQuerymethod to create aQueryobject, passing the HQL statement and the entity class as parameters. Uses theQueryobject'ssetParametermethod to set query parameters, where0indicates the parameter position andnameindicates the parameter value. Uses theQueryobject'slistmethod to execute the query and converts the query results into a list ofUserobjects.Sample code:
public List<User> selectUserbyName(String name) { String sql = "FROM test_hibernate_oracle 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 aSessionobject 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.Sample code:
public List<User> selectUser() { String sql = "SELECT * FROM test_hibernate_oracle"; 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 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 persist the user object to the database. Obtain 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.Sample code:
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 specified ID from the database. Specify an integer parameteridto pass 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. Obtain 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.Sample code:
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 aSessionobject to start a transaction. Use thegetmethod of aSessionobject to obtain the correspondingUserobject based on the user ID. Use themergemethod of aSessionobject to merge the passedUserobject with the obtainedUserobject, updating the passed user data to the database. Obtain the current transaction by calling thegetTransactionmethod of theSessionand call thecommitmethod to commit the transaction, returning the result of the modification operation.Sample code:
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; }
Introduction to 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.
Sample code:
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_oracle.Sample code:
@Entity @Table(name = "test_hibernate_oracle")Define the
Userclass.This class is used to map to a table named
test_hibernate_oraclein 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 designate 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.Sample code:
@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.Sample code:
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.Sample code:
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 caller.Sample code:
@Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; }
Introduction to 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 consists of 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.Sessioninterface: Used for session operations with the database.SessionFactoryinterface: 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.Listinterface: Used to store query result sets.UUIDclass: Used to generate unique identifiers.
Code:
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.Code:
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 sample code
<?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>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</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_oracle">
<!-- 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.oceanbase.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>
<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.Oracle12cDialect</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_oracle 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_oracle";
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_oracle")
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