Hibernate升级后注解方式的对象关系映射
我要说的升级指的是我实际中遇到的,由于我之前的项目中Hibernate是3.3.2版本的,那时关于Annotation注解方式的对象关系映射得依赖这么几个包:
hibernate-annotations.jar,
ejb3-persistence.jar
hibernate-commons-annotations.jar
所以之前的项目如果更换为3.5.3版本后(当前最新发布的最终版本是3.6.0),那么这三个依赖包都会没有了,取而代之的是
\hibernate-distribution-3.6.0.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.0.Final.jar
也就是说这个hibernate-jpa-2.0-api-1.0.0.Final.jar能够代替上面的三个包的作用
先回顾下一个简单的注解方式的例子
User.java
- <span style="font-size: large;">package com.javacrazyer.test;
- 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 = "user")
- // 非必要,在表格名称与类别名称不同时使用
- public class User {
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Integer id;
- @Column(name = "name")
- // 非必要,在字段名称与属性名称不同时使用
- private String name;
- @Column(name = "age")
- private Integer age; // 非必要,在字段名称与属性名称不同时使用
- // 必须要有一个预设的建构方法
- // 以使得Hibernate可以使用Constructor.newInstance()建立对象
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- }
- </span>
Category.java
- <span style="font-size: large;">package com.javacrazyer.test;
- import java.io.Serializable;
- import java.util.ArrayList;
- import java.util.List;
- import javax.persistence.CascadeType;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.ManyToOne;
- import javax.persistence.OneToMany;
- import javax.persistence.Table;
- import javax.persistence.Version;
- /**
- * 产品类别
- *
- */
- @Entity
- @Table(name="category")
- public class Category implements Serializable{
- private static final long serialVersionUID = -3942148673242309324L;
- @Id
- @GeneratedValue
- private Integer id;
- @Version
- private Integer version;
- private String name;
- private String description;
- private String path; //分类路径
- //Category 自身双向多对一
- @ManyToOne(cascade={CascadeType.MERGE,CascadeType.PERSIST})
- private Category parent;
- //Category 自身双向一对多
- @OneToMany(mappedBy="parent",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
- @JoinColumn(name="parent_id")
- private List<Category> child = new ArrayList<Category>();
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public Category getParent() {
- return parent;
- }
- public void setParent(Category parent) {
- this.parent = parent;
- }
- public List<Category> getChild() {
- return child;
- }
- public void setChild(List<Category> child) {
- this.child = child;
- }
- public Integer getVersion() {
- return version;
- }
- @SuppressWarnings("unused")
- private void setVersion(Integer version) {
- this.version = version;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- }</span>
hibernate.cfg.xml
- <span style="font-size: large;"><?xml version="1.0" encoding="utf-8" ?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- 显示实际操作数据库时的SQL -->
- <property name="show_sql">true</property>
- <!-- SQL方言,这边设定的是MySQL -->
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <!-- JDBC驱动程序 -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <!-- JDBC URL -->
- <property name="connection.url">jdbc:mysql:///test</property>
- <!-- 数据库使用者 -->
- <property name="connection.username">root</property>
- <!-- 数据库密码 -->
- <property name="connection.password">root</property>
- <property name="default_batch_fetch_size">10</property>
- <property name="hibernate.current_session_context_class">thread</property>
- <property name="show_sql">true</property>
- <property name="format_sql">true</property>
- <property name="hbm2ddl.auto">update</property>
- <!-- 以下设置对象与数据库表格映像类别 -->
- <mapping class="com.javacrazyer.test.User"/>
- <mapping class="com.javacrazyer.test.Category"/>
- </session-factory>
- </hibernate-configuration></span>
Hibernate工具类
- <span style="font-size: large;">package com.javacrazyer.common;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.AnnotationConfiguration;
- /**
- * Hibernate工具类
- *
- */
- public class HibernateUtil {
- private static final SessionFactory factory;
- private HibernateUtil(){}
- static{
- //加载Hibernate全局配置文件,根据配置信息创建SessionFactory工厂实例
- factory = new AnnotationConfiguration().configure().buildSessionFactory();
- }
- public static SessionFactory getSessionFactory(){
- return factory;
- }
- /**
- * 本方法用来获取当前线程上绑定的Session实例
- * 注意hibernate全局配置文件中,如果使用是JDBC事务,添加如下配置:<br/>
- * <property name="hibernate.current_session_context_class">thread</property>
- * @return
- */
- public static Session getSession(){
- return factory.getCurrentSession();
- }
- }
- </span>
测试类
- <span style="font-size: large;">package com.javacrazyer.test;
- import java.util.ArrayList;
- import java.util.List;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.junit.BeforeClass;
- import org.junit.Test;
- import com.javacrazyer.common.HibernateUtil;
- public class MyTest {
- private static SessionFactory sf;
- @BeforeClass
- public static void init() {
- sf = HibernateUtil.getSessionFactory();
- }
- @Test
- public void useradd() {
- User user = new User();
- user.setName("caterpillar");
- user.setAge(new Integer(30));
- // 开启Session,相当于开启JDBC的Connection
- Session session = sf.getCurrentSession();
- // Transaction表示一组会话操作
- Transaction tx = session.beginTransaction();
- // 将对象映像至数据库表格中储存
- session.save(user);
- tx.commit();
- System.out.println("新增资料OK!请先用MySQL观看结果!");
- }
- @Test
- public void categoryadd(){
- Category category=new Category();
- category.setName("类别1");
- Category category1=new Category();
- category1.setName("类别1-01");
- category1.setParent(category);
- Category category2=new Category();
- category2.setName("类别1-02");
- category2.setParent(category);
- List<Category> childs=new ArrayList<Category>();
- childs.add(category1);
- childs.add(category2);
- category.setChild(childs);
- Session session = sf.getCurrentSession();
- // Transaction表示一组会话操作
- Transaction tx = session.beginTransaction();
- session.persist(category);
- tx.commit();
- }
- }
- </span>
对于User的持久化操作相当顺利,这个升级过程是成功的。
但是对于Category的升级就没那么容易了,如果不细心发现的话,总是报
Associations marked as mappedBy must not define database mappings like @JoinTable or @JoinColumn
或者是Unrooted Test之类的错误
错误发生在下面这些代码中
@OneToMany(mappedBy="parent",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name="parent_id")
private List<Category> child = new ArrayList<Category>();
后来发现在3.5.3版本中@JoinColumn与mappingBy是互斥的,之前在hibernate.3.3.2中都是正确无误的,也就是hibernate.3.3.2允许这两个互相存在。所以呢,如果升级到hibernate3.5.3想测试成功的话,mappBy="parent",就应该去掉,正确的配置应该是这样
@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name="parent_id")
private List<Category> child = new ArrayList<Category>();
索性将mappingBy再温习下
a) 只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性;
b) mappedBy标签一定是定义在the owned side(被拥有方的),他指向the owning side(拥有方);
c) mappedBy的含义,应该理解为,拥有方能够自动维护 跟被拥有方的关系;
当然,如果从被拥有方,通过手工强行来维护拥有方的关系也是可以做到的。
d) mappedBy跟JoinColumn/JoinTable总是处于互斥的一方,可以理解为正是由于拥有方的关联被拥有方的字段存在,拥有方才拥有了被 拥有方。mappedBy这方定义的JoinColumn/JoinTable总是失效的,不会建立对应的字段或者表
明天你还会爱我?