对象表映射
实体类--数据库表间的转换
由于Hibernate的存储都是建立在对象基础上的,所以映射好实体类对象和数据库表是非常重要的,数据库表的设计也必须按照一定的规范来(冗余字段等就不允许存在?)
本章的目录:
1.简单对象表映射
--搭建JUnit测试环境
附:
搭建JUnit测试环境
1.去官网下载jar包
2.解压,复制junit-4.10.jar(我用的此时是4.10版本)到bin下的jar中
3.在项目名上右键→new→Source Folder→输入名称→finish
4.注意,你对哪个包进行测试,你就在测试下建立和那个包相同的包
5.建立测试类,需要在测试的方法前面加入”@Test”
1.简单对象表映射,(单表无关联)
先把实体类贴出来(本人英文名jake,无需吐槽包名)
package com.jake.hibernate.domain;
import java.util.Date;
public class Person {
private long id;
private String name;
private Date birthday;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
然后是映射文件:建议与实体类同包,名字为 实体类名.hbm.xml
<?xml version="1.0"?> <!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.jake.hibernate.domain"> <class name="Person" table="PERSON"> <id name="id" column="id"> <generator class="native" /> </id> <property name="name" column="name" /> <property name="birthday" type="timestamp" column="birthday" /> </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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernateTest</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">10</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <mapping resource="com/jake/hibernate/domain/Person.hbm.xml" /> <!-- <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml" /> <mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml" /> --> </session-factory> </hibernate-configuration>
接下来是JUnit Test的代码
package com.jake.hibernate.domain;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.jake.hibernate.util.HibernateUtil;
public class TestPerson {
private static SessionFactory sf = null;
@BeforeClass
// 表示Junit此类被加载到内存中就执行这个方法
public static void beforClass() {
sf = HibernateUtil.getSessionFactory();
}
@Test
public void TestPerson() {
Session session = sf.getCurrentSession();
session.beginTransaction();
Person p = new Person();
p.setName("jake");
Date d = new Date();
p.setBirthday(d);
session.save(p);
session.getTransaction().commit();
// session.close();
// 注意,commit后是自动关闭session的,不需要是手动close
}
@AfterClass
public static void afterClass() {
sf.close();
}
}
测试成功。。
有一点出乎意料的地方是,数据库生成的是datetime型的,不是timestamp。
目前未解决。。
接下来是annotation版本的了。。
实体类
package com.jake.hibernate.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "t_person")
public class Person {
private long id;
private String name;
private Date birthday;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
配置文件
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernateTest</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">10</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping class="com.jake.hibernate.model.Person"/> </session-factory> </hibernate-configuration>
刚开始漏掉了
<mapping class="com.jake.hibernate.model.Person"/>
可把我整惨了,以为是实体类哪里写错了,唉。久没写了。
这个是HibernateUtil-----实验证明AnnotationConfiguration已经过时了
package com.jake.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
JUnitTest 的代码也贴了吧~~
package com.jake.hibernate.model;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.jake.hibernate.util.HibernateUtil;
public class PersonTest {
static SessionFactory sf = null;
@BeforeClass
public static void beforeClass() {
sf = HibernateUtil.getSessionFactory();
}
@org.junit.Test
public void PersonTest() {
Session session = sf.getCurrentSession();
session.beginTransaction();
Person p = new Person();
Date birthday = new Date();
p.setBirthday(birthday);
p.setName("jake");
session.save(p);
session.getTransaction().commit();
}
@AfterClass
public static void afterClass() {
sf.close();
}
}
OK。测试成功。。。