在Spring框架中集成JPA实例

开发 后端
本文向您介绍在Spring框架中集成JPA的实例,包括持久层DAO接口的编写和Spring的配置等。

Hibernate 3.2支持JPA注解,Spring集成JPA是可选的。

下面是Spring集成JPA的一个例子。

实体类MyUser,使用JPA注解实现到数据库表myUser的映射,如下所示:

   package org.shirdrn.entity;
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.Transient;
@Entity
public class MyUser {
private Long id;
private String userName;
private String password;
private String gender;
private Integer age;
private Integer birthYear;
private String addr;
private String email;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
   return id;
}
public void setId(Long id) {
   this.id = id;
}
@Column(name="userName")
public String getUserName() {
   return userName;
}
public void setUserName(String userName) {
   this.userName = userName;
}
@Column(name="password")
public String getPassword() {
   return password;
}
public void setPassword(String password) {
   this.password = password;
}
@Column(name="gender")
public String getGender() {
   return gender;
}
public void setGender(String gender) {
   this.gender = gender;
}
@Column(name="age")
public Integer getAge() {
   return age;
}
public void setAge(Integer age) {
   this.age = age;
}
@Column(name="addr")
public String getAddr() {
   return addr;
}
public void setAddr(String addr) {
   this.addr = addr;
}
@Column(name="email")
public String getEmail() {
   return email;
}
public void setEmail(String email) {
   this.email = email;
}
@Transient
public Integer getBirthYear() {
   return new Integer(2008-age);
}
public void setBirthYear(Integer age) {
   this.birthYear = new Integer(2008-age);
}
}


其中,birthYear不是数据库中的字段,使用JPA的@Transient注解,在映射的时候,会忽略掉该成员。

持久层DAO接口如下:

   package org.shirdrn.dao;
import java.util.List;
import org.shirdrn.entity.MyUser;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface MyUserDAO {
public void createMyUser(MyUser myUser);
public void deleteMyUser(MyUser myUser);
public void updateMyUser(MyUser myUser);
public List queryMyUser(String queryString);
public List queryAll();
}


这里,使用了JPA注解,声明事务。

DAO实现类,如下所示:

    package org.shirdrn.dao.impl;
import java.util.List;
import org.shirdrn.dao.MyUserDAO;
import org.shirdrn.entity.MyUser;
import org.springframework.orm.jpa.support.JpaDaoSupport;
public class MyUserDAOImpl extends JpaDaoSupport implements MyUserDAO {
public void createMyUser(MyUser myUser) {
   getJpaTemplate().persist(myUser);
}
public void deleteMyUser(MyUser myUser) {
   MyUser dbMyUser = getJpaTemplate().find(MyUser.class, myUser.getId());
   getJpaTemplate().remove(dbMyUser);
}
public void updateMyUser(MyUser myUser) {
   MyUser dbMyUser = getJpaTemplate().find(MyUser.class, myUser.getId());
   if(myUser.getUserName() != null){
    dbMyUser.setUserName(myUser.getUserName());
   }
   if(myUser.getAddr() != null){
    dbMyUser.setAddr(myUser.getAddr());
   }
   getJpaTemplate().merge(dbMyUser);
}
@SuppressWarnings("unchecked")
public List queryMyUser(String queryString) {
   return (List)getJpaTemplate().find(queryString);
}
@SuppressWarnings("unchecked")
public List queryAll() {
   return (List)getJpaTemplate().find("from MyUser");
}
}


因为继承了JpaDaoSupport,索引需要获取一个JpaTemplate来实现访问数据库,在Spring的配置文件中要注入一个org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean。#p#

Spring的配置文件applicationContext.xml的内容如下所示:

   
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">




















abstract="false"lazy-init="default"autowire="default"
dependency-check="default">




 

在META-INF目录下,还要加一个persistence.xml配置文件,如下所示:
    
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">

org.hibernate.ejb.HibernatePersistence
org.shirdrn.entity.MyUser


接着,对增删改查操作进行测试,如下所示:

插入记录:

   packageorg.shirdrn.test;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassTestCreateMyUser{
publicstaticvoidmain(String[]args){
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
MyUsermyUser=newMyUser();
myUser.setUserName("JohnXa");
myUser.setPassword("123456");
myUser.setGender("男");
myUser.setAge(newInteger(25));
myUser.setAddr("NewYork");
myUser.setEmail("john@hotmail.com");
myUserDAO.createMyUser(myUser);
}
}

删除记录:
    packageorg.shirdrn.test;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.ClassPathXmlApplicationContext;
publicclassTestDeleteMyUser{
publicstaticvoidmain(String[]args){
ApplicationContextctx=newClassPathXml("applicationContext.xml");
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
MyUsermyUser=newMyUser();
myUser.setId(newLong(29));
myUserDAO.deleteMyUser(myUser);

修改记录:
    packageorg.shirdrn.test;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ClassPathXmlApplicationContext;

 

publicclassTestUpdateMyUser{
publicstaticvoidmain(String[]args){
ApplicationContextctx=newClassPathXmlApplicationContext("applicationContext.xml");
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
MyUsermyUser=newMyUser();
myUser.setId(newLong(28));
myUser.setAddr("北京市");
myUserDAO.updateMyUser(myUser);
}
}


查询记录:
   packageorg.shirdrn.test;
importjava.util.List;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ClassPathXmlApplicationContext;
publicclassTestQueryAllMyUser{
publicstaticvoidmain(String[]args){
ApplicationContextctx=newClassPathXmContext("applicationContext.xml");
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
Listlist=myUserDAO.queryMyUser("fromMyUser");
for(MyUseruser:list){
System.out.println("ID:"+user.getId()+
"|姓名:"+user.getUserName()+
"|密码:"+user.getPassword()+
"|性别:"+user.getGender()+
"|年龄:"+user.getAge()+
"|住址:"+user.getAddr()+
"|邮箱:"+user.getEmail());
}
}
}

心得总结

感觉自己对JPA的理解还是不怎么深刻。

JpaTemplate提供的一些操作的方法,感觉不是很快就能理解的。

似乎使用JpaTemplate没有使用HibernateTemplate方便,尤其是在执行插入、修改、删除记录的时候。修改和删除记录需要先把数据库中对应的记录加载出来,才能执行修改和删除操作。

查询数据库倒是很容易,因为根本不需要事务,如果没有事务,插入、修改和删除操作就不能实现。

在Spring中使用JPA,感觉代价比较大,使用起来不容易,出错不容易调试。

比较好的地方就是。如果数据库中的表很多,无需编写大量的XML文件去映射,而且只需要从POJO中就可以非常直观地看到各个表之间的关系。

您正在阅读:在Spring框架中集成JPA实例

【编辑推荐】

  1. Spring中文手册RC2随Spring2.0同步全球发行
  2. Eclipse开发: Struts 2 + Spring 2 + JPA + AJAX
  3. Spring 2.5 中配置 JPA
责任编辑:张攀 来源: 百度空间
相关推荐

2024-01-31 09:42:11

RabbitMQ消息队列.NET

2009-06-23 09:33:20

FCKEditorJSFJSP

2011-07-20 17:10:05

iPhone iAd

2014-12-31 09:56:29

Ehcache

2009-01-03 14:43:55

ibmdwPHPsMash

2014-09-28 14:53:39

渗透BurpSuiteSqlmap

2011-06-29 09:42:12

Visual Stud Qt Opensource

2009-06-18 15:28:08

Glassfish JSpring

2009-01-03 15:01:16

ibmdwLptus

2009-06-11 13:28:18

Glassfish集成

2016-04-20 09:47:40

MapBoxAndroid地图

2011-03-04 09:40:42

AJAX开发集成数据库

2012-10-18 10:12:42

IBMdw

2024-01-03 07:19:19

LogbackLog4j2Java

2009-06-19 16:25:34

Flex与Spring

2011-03-02 17:42:35

2012-03-06 11:25:40

ibmdw

2009-06-01 14:32:10

jpa技术Java框架

2009-06-18 15:56:49

Struts和Spri

2009-03-24 10:30:35

SpringStruts集成
点赞
收藏

51CTO技术栈公众号