Spring+JPA(hibernate)整合 一对多及继承关系配置

花了三天时间总算把spring+JPA搞定了。例子涉及OneToMany(单向,外键关联主键)的映射,和主pojo的继承关系。

看一下域对象及数据库关系图:

Spring+JPA(hibernate)整合 一对多及继承关系配置

pojo,父类(Topic):

@Entity(name="t_topic")
//父子同一个表
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
//区分父子pojo的字段,在这里预设父类的"topic_type"等于"a"
@DiscriminatorColumn(name="topic_type", discriminatorType=DiscriminatorType.STRING,length=2)
@DiscriminatorValue(value="a")
public class Topic implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="topic_id")
    private int topicId;
    
    @Column(name="topic_title",length=100)
    private String topicTitle;
    
    //java.sql.Date 时间类型
    @Temporal(TemporalType.DATE)
    @Column(name="topic_time")
    private Date topicTime;
    
    @Column(name="topic_views")
    private int topicViews;
    
    setter & getter...
}


子类(PollTopic):

@Entity
@DiscriminatorValue(value="b")
public class PollTopic extends Topic{
    
    private boolean multiple;
    
    @Column(name="max_choices")
    private int maxChoices;
    
    /**
     * @OneToMany中通过mappedBy属性指定“Many”方类引用“One”方类的属性名,
     * 这里 mappedBy="pollTopic"表示 PollOption实体拥有一个指定 PollTopic的pollTopic属性。  
     */
    @OneToMany(mappedBy="pollTopic",cascade=CascadeType.ALL)
    private Set<PollOption> options=new HashSet<PollOption>();

    setter and getter..
}



OneToMany里“Many”的pojo:

@Entity
@Table(name="t_poll_option")
public class PollOption implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="option_id")
    private int id;
    
    @Column(name="option_item")
    private String optionItem;
    
    @ManyToOne
    @JoinColumn(name="topic_id",nullable=false)
    private PollTopic pollTopic;
    
    setter and getter...
}



spring的配置文件 applicationContext.xml: (Jpa相关的配置,非全部)

	<bean id="myEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="test" />
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory">
		  <ref bean="myEntityManagerFactory" />
		</property>
		<property name="jpaDialect" >
		  <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		</property>
	</bean>
    <!-- DAO的配置,需实现一个DAO的接口,否则会出现类型转换异常-->
	<bean id="jpaDaoImpl" class="jpa.dao.JpaDaoImpl">
        <property name="entityManagerFactory">
            <ref bean="myEntityManagerFactory" />
        </property>
	</bean>


Jpa的配置文件 persistence.xml(需放在src/META-INF目录下)
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
  <!-- name和spring里面的配置要一致 -->
  <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
  </persistence-unit>
</persistence>


最后来看一下DAO的2个类

//声明事务
@Transactional
public interface JpaDao {
    public void save(Object obj);
}

//这里一定要实现一个Dao的接口,全当时编码规范吧,因为这个接口耽误了我很多时间,总是出一些莫名奇妙的错误!
public class JpaDaoImpl extends JpaDaoSupport implements JpaDao{
    public void save(Object obj){
	getJpaTemplate().persist(obj);
    }
}



测试类:

public class TestAnnotation extends TestCase {
    
    static ApplicationContext ctx =null;
    static{
	ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    public void testOneToMany() {
	JpaDao dao=(JpaDao) ctx.getBean("jpaDaoImpl");
	
	PollTopic topic = new PollTopic();
	topic.setTopicTime(new Date());
	topic.setTopicTitle("yangyang");
	topic.setTopicViews(10);
	topic.setMultiple(false);
	topic.setMaxChoices(3);

	PollOption option = new PollOption();
	option.setOptionItem("选举");
	
	option.setPollTopic(topic);
	topic.getOptions().add(option);
	
	dao.save(topic);

    }
    


这里面主要是参照附件里的JPA_Basic.pdf里的一多关系例子,同时附上源码,里面有一个Person的HelloWorld很简单,如果看不明白可以先看下这个。

依赖的类库:

Spring+JPA(hibernate)整合 一对多及继承关系配置

notice:采用hibernate3.3+spring2.6 其中涉及到lib的 hibernate-distribution-3.3.2.GA,hibernate-annotations-3.4.0.GA,hibernate-entitymanager-3.4.0.GA,hibernate-entitymanager-3.4.0.GA 请按版本号到官网下载,否则总会出现一些莫名其妙的异常让你很郁闷。


你可能感兴趣的:(DAO,spring,Hibernate,xml,jpa)