Define a domain model class that represents database table structure:
package com.example.elec.domain;
import java.io.Serializable;
import java.util.Date;
public class DeviceLog implements Serializable {
private String logId;
private String deviceName;
private Date logDate;
private String description;
// Accessor methods
public String getLogId() { return logId; }
public String getDeviceName() { return deviceName; }
public Date getLogDate() { return logDate; }
public String getDescription() { return description; }
// Mutator methods
public void setLogId(String id) { this.logId = id; }
public void setDeviceName(String name) { this.deviceName = name; }
public void setLogDate(Date date) { this.logDate = date; }
public void setDescription(String desc) { this.description = desc; }
}
Configuring Hibernate Mapping File
Create XML mapping configuration for the domain class:
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-mapping>
<class name="com.example.elec.domain.DeviceLog" table="DEVICE_LOGS">
<id name="logId" type="string">
<column name="LOG_ID" length="50" not-null="true"/>
<generator class="uuid"/>
</id>
<property name="deviceName" type="string">
<column name="DEVICE_NAME" length="50"/>
</property>
<property name="logDate" type="java.util.Date"/>
<property name="description" type="string">
<column name="DESCRIPTION" length="500"/>
</property>
</class>
</hibernate-mapping>
Setting Up Hibernate Configuration
Configure databace connection properties:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/device_logs</property>
<property name="connection.username">root</property>
<property name="connection.password">secure123</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="com/example/elec/domain/DeviceLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Testing the Persistence Layerr
Create a JUnit test to verify database operasions:
package com.example.test;
import com.example.elec.domain.DeviceLog;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import java.util.Date;
public class PersistenceTest {
@Test
public void testSaveLog() {
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
DeviceLog log = new DeviceLog();
log.setDeviceName("Temperature Sensor");
log.setDescription("Initial calibration complete");
log.setLogDate(new Date());
session.save(log);
tx.commit();
session.close();
}
}