由于Hibernate 4版本混乱,Hibernate 3有些过时,Hibernate 5的开发文档尚不完善,所以构建一份简单的Hibernate 5的入门指南
注:案例参考Hibernate 官方参考文档,使用Hibernate 5.3.7 、Java 8 -191、MySQL 8.0. 13进行修改测试
本案例使用hbm.xml映射文件创建简单的Hibernate测试项目
-
首先创建hibernate.cfg.xml配置文件并做简单的配置。
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.url">jdbc:mysql://localhost:3306/databaseName?useSSL=false&serverTimezone=UTC&verifyServerCertifate=false&allowPublicKeyRetrieval=true</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">passwd</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!--先定义为create使其在数据库生成对应的表,之后可以修改为update-->
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
</session-factory>
</hibernate-configuration> -
创建实体Java类
import java.util.Date;
public class Event {
private Long id;
private String title;
private Date date;
public Event() {
}
public Event(String title, Date date) {
this.title = title;
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
} -
创建Event.hbm.xml映射文件
<hibernate-mapping package="类路径">
<class name="Event" table="EVENTS">
<!--定义id映射元素主键自增-->
<id name="id" column="EVENTS_ID">
<generator class="increment"/>
</id>
<!--定义属性映射元素-->
<property name="date" column="EVENT_DATE" type="timestamp"/>
<property name="title"/>
</class>
</hibernate-mapping> -
向hibernate.cfg.xml文件中添加映射信息
<mapping resource="类路径/Event.hbm.xml"/>
-
JUnit测试测试程序
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import junit.framework.TestCase;
public class NativeApiIllustrationTest extends TestCase {
private SessionFactory sessionFactory;
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
@Override
protected void tearDown() throws Exception {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
@SuppressWarnings("unchecked")
public void testBasicUsage() {
// create a couple of events...
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Event( "Our very first event!", new Date() ) );
session.save( new Event( "A follow up event", new Date() ) );
session.getTransaction().commit();
session.close();
// now lets pull events from the database and list them
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( "from Event" ).list();
for ( Event event : (List<Event>) result ) {
System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() ); } session.getTransaction().commit(); session.close(); }} 运行测试