萧萧风 / Spring / spring整合JPA总结

0 0

   

spring整合JPA总结

2012-07-11  萧萧风

1、定义实体类

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity // 表明该类 (RtoUser ) 为一个实体类,如果写成@Entity(RtoUserTable)它对应数据库中的表表名是RtoUserTable;

            //写成@Entity则默认对应表RtoUser,和类名称相同
public class RtoUser implements Serializable{

 /**
  *
  */
 private static final long serialVersionUID = 1L;

 @Id //指定userName为主键
 private String userName;  
 private String password;

 @Column(length = 30)
 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 @Column(length = 30)
 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

}
2.定义Dao接口

import java.util.List;

/**

* 该接口定义操作数据库的抽象方法,方法体由具体类去实现

*/

public interface BaseDao {
    public abstract void save (Object object);
    public abstract void update (Object object);
    public abstract Object find(Object object);
    public abstract List findByCondition(String conditions);
    public abstract void deleteByCondition(String conditions);
    public abstract void delete(Object object);
}

3.定义具体类

import java.util.List;

import java.util.List;

import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.huahuan.devicemanager.common.entity.RtoUser;
import com.huahuan.devicemanager.server.dao.BaseDao;

@Transactional
@SuppressWarnings("deprecation")
public class RtoUserDaoImpl extends JpaDaoSupport  implements BaseDao { //实体的具体Dao类必须继承JpaDaoSupport类

 @Override
 public void save(Object object) {
  object = (RtoUser) object;

  this.getJpaTemplate().persist(object);

 }

 @Override
 public void update(Object object) {
  RtoUser rtoUser = (RtoUser) object;
  this.getJpaTemplate().merge(rtoUser);
 }

 @Override
 public Object find(Object object) {
   RtoUser rtoUser = (RtoUser) object;
   rtoUser = this.getJpaTemplate().find(rtoUser.getClass(),
    rtoUser.getUserName());
  return rtoUser;
 }

 @Override
 @SuppressWarnings("unchecked")
 public List<RtoUser> findByCondition(String conditions) {
  return null;
 }

 @Override
 public void deleteByCondition(String conditions) {

 }

 @Override
 public void delete(Object object) {
  object = (RtoUser) object;
  this.getJpaTemplate().remove(this.getJpaTemplate().merge(object));
 }

 }
4.persistence.xml配置文件

注:在java应用中,该文件一定要方法哦src/META-INF/下

<?xml version="1.0" encoding="UTF-8"?>

<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_2_0.xsd"
 version="2.0">

 <!-- 持久化单元 name:持久化单元的名称,集成时会在spring配置文件中使用 transaction-type:事务类型 RESOURCE_LOCAL或JTA,j2ee环境下默认是jta,j2se环境下默认是RESOURCE_LOCAL -->

 <persistence-unit name="jpa" transaction-type="RESOURCE_LOCAL">

  <!-- 持久化技术提供商 Hibernate -->
  <provider>org.hibernate.ejb.HibernatePersistence</provider>

  <!-- 实体类 -->
  <!-- 用户实体:必须在此定义实体类,否则加载时会包实体未定义异常 -->
  <class>com.huahuan.devicemanager.common.entity.RtoUser</class>

  <!-- 具体产品的配置信息 -->
  <properties>
   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
   <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />

   <property name="hibernate.connection.username" value="root" />

   <property name="hibernate.connection.password" value="admin" />

   <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test" />

   <property name="hibernate.show_sql" value="true" />

   <!--hibernate.hbm2ddl.auto属性,当值为create时,每次启动应用就会删除旧表结构,重新创建最新的表结构,数据会丢失;

        当值为update时,每次启动应用,如果实体类有变化的话,就会在原来表结构的基础上新建,原始数据不会丢失;

   -->

   <property name="hibernate.hbm2ddl.auto" value="update" />

  </properties>
 </persistence-unit>
</persistence>

5.applicationContext.xml配置

j2se应用放到src/下

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"

 xmlns:context="http://www.springframework.org/schema/context"

 xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-2.5.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">

 <!--自动扫描注解 @Resource、@Service、@PersistenceContext等。 -->
 <context:component-scan base-package="com.huahuan.devicemanager.server*"></context:component-scan>

 <bean id="rtoUserDao"
  class="com.huahuan.devicemanager.server.dao.impl.RtoUserDaoImpl">
  <property name="jpaTemplate" ref="jpaTemplate" /><!-- 为实体Dao注入jpaTemplate实例,该配置必须有-->
 </bean>

 <!--实体管理器工厂,spring整合jpa的入口,不能自定义数据源 jpa:是持久化单元的名称 -->
 <bean id="lemfb"
  class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
  <property

name="persistenceUnitName" value="jpa"></property>

<!--持久化单元名称,其中jpa是在persistence.xml中定义的;-->

<!--另外注意property属性中value和ref的区别,个人理解:

value是给属性赋一个默认值,如<property

name="persistenceUnitName" value="jpa" />的意思是,让persistenceUnitName的值为jpa;而ref是指将ref指定的对象实例赋值给对应的属性,ref指定的对象实例在配置文件中通过bean标签定义-->
 </bean>

 <!-- 配置事务管理器 JpaTransactionManager -->
 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="lemfb"></property>
 </bean>

<!-- 定义JpaTemplate --> 

<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
  <property name="entityManagerFactory" ref="lemfb"/>
 </bean>
 <!-- 配置注解@Transactional的驱动,如果要想使用该注解,必须有tx:annotation-driven配置 -->
 <tx:annotation-driven transaction-manager="transactionManager"/>

 <!-- 编写通知 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" />

   <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" />

   <tx:method name="get*" propagation="REQUIRED" isolation="DEFAULT"
    read-only="true" />

   <tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT"
    read-only="true" />

   <tx:method name="load*" propagation="REQUIRED" isolation="DEFAULT"
    read-only="true" />

   <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />

  </tx:attributes>
 </tx:advice>

 <!-- 编写aop配置(通知切入点 advisor) -->

<!-- spring进行事务管理时,有proxy-target-class属性,该属性作用为定义事务dao是接口还是类,默认为false,即事物dao为接口;

      如果dao为实现类时就会报“Failed to convert property value of type '$Proxy15”或“'$ProxyXX' can not be casted to XXX.java ”,此时将 proxy-target-class设置为true就可以了 --> 

<aop:config proxy-target-class="true">
  <aop:advisor pointcut="execution(* *..*Service.*(..))"
   advice-ref="txAdvice" />
 </aop:config>
</beans>
6.测试类

 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.huahuan.devicemanager.common.entity.RtoUser;
import com.huahuan.devicemanager.server.dao.BaseDao;

public class SpringJpaTest {
 public static void main(String[] args){
  ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  BaseDao baseDao = (BaseDao) ac.getBean("rtoUserDao");
  RtoUser rtoUser = new RtoUser();
  rtoUser.setUserName("at6");
  rtoUser.setPassword("1");
  while(true){
   if(null == baseDao.find(rtoUser)){
    baseDao.save(rtoUser);
    rtoUser = (RtoUser) baseDao.find(rtoUser);
   } else {
    rtoUser = (RtoUser) baseDao.find(rtoUser);
   }
   System.out.println("用户名:"+rtoUser.getUserName()+"\n"+"密     码:"+rtoUser.getPassword());
  }
 }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。如发现有害或侵权内容,请点击这里 或 拨打24小时举报电话:4000070609 与我们联系。

    猜你喜欢

    0条评论

    发表

    请遵守用户 评论公约

    类似文章
    喜欢该文的人也喜欢 更多