二、JPA和Spring集成

一、千里之行始于新建工程导入jar包

antlr-2.7.7.jar
c3p0-0.9.2.1.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ehcache-core-2.4.3.jar
hibernate-c3p0-4.2.4.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.4.Final.jar
hibernate-ehcache-4.2.4.Final.jar
hibernate-entitymanager-4.2.4.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
mchange-commons-java-0.2.3.4.jar
mysql-connector-java-5.1.7-bin.jar
slf4j-api-1.6.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

二、和Spirng集成配置web.xml岂能少?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JPA_Spring</display-name>
 
  <!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
</web-app>

三、最为核心的还是application.xml文件的配置
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <context:component-scan base-package="com.tan.jpa"></context:component-scan>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="root"></property>
		<property name="password" value="123456"></property>
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///jpa"></property>	
	</bean>
	
	<!-- 配置 EntityManagerFactory. 使用 LocalContainerEntityManagerFactoryBean -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		
		<!-- 实体类所在的包 -->
		<property name="packagesToScan" value="com.tan.jpa.spring.entities"></property>	
		
		<!-- *配置 JPA 实现产品的适配器 -->
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
		</property>
		
		<!-- 配置 JPA 的具体的属性 -->
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
				
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<!-- *配置自动生成数据表列名的策略. 例如: lastName - last_name -->
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
			</props>
		</property>
	</bean>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"></property>	
	</bean>
	
	<tx:annotation-driven transaction-manager="transactionManager"/>



</beans>

四、再整一个实体Entity来,不然下面没法继续。。

package com.tan.jpa.spring.entities;

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;
import javax.persistence.Transient;

import org.hibernate.annotations.NamedQuery;

@NamedQuery(name="ALL_STUDENTS",query="FROM Student")
@Table(name="JPA_STUDENTS")
@Entity
public class Student {

	private Integer id;
	private String lastName;
	private String school;
	
	private Date birth;
	
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Id
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name="LAST_NAME")
	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}

	@Temporal(TemporalType.DATE)
	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	//该方法对应的 info 不需要映射为数据表的列. 
	@Transient
	public String getInfo(){
		return lastName + ":" + school;
	}

	public Student(Integer id, String lastName) {
		super();
		this.id = id;
		this.lastName = lastName;
	}
	
	public Student() {
		// TODO Auto-generated constructor stub
	}

	public Student(String lastName, String school, Date birth) {
		super();
		this.lastName = lastName;
		this.school = school;
		this.birth = birth;
	}
}

五、实体类整完了, 要和数据库打交道那就整一个DAO吧!

package com.tan.jpa.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import com.tan.jpa.spring.entities.Student;

@Repository
public class StudentDao {
	//使用持久化执行上下文将EntityManager实例注入进来
	@PersistenceContext
	private EntityManager entityManager;
	
	public StudentDao() {
		System.out.println("构造方法StudentDao....");
	}
	
	public void save(Student stu){
		entityManager.persist(stu);
	}
	
	public Student findOne(Integer id){
		return entityManager.find(Student.class, id);
	}			
}

六、DAO层有了,我们习惯上再整一个Service层来添加业务,虽说这里面没有,但是也要加上事务。

package com.tan.jpa.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tan.jpa.dao.StudentDao;
import com.tan.jpa.spring.entities.Student;

@Service
public class StudentService {
	@Autowired
	private StudentDao studentDao;
	
	//批量保存操作
	@Transactional
	public void save(Student...stu){
		for (Student s:stu) {
			studentDao.save(s);
		}
	}
	@Transactional
	public Student findOne(Integer id){
		return studentDao.findOne(id);
	}
}

七、所有的东西都已就绪,开测吧~

package com.tan.jpa.test;

import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tan.jpa.service.StudentService;
import com.tan.jpa.spring.entities.Student;

public class Test {
	@org.junit.Test
	public void test() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
		StudentService studentService = ctx.getBean(StudentService.class);
		
		//测试查询
		Student findOne = studentService.findOne(3);
		System.out.println("id="+findOne.getId()+"   LastName:"+findOne.getLastName());
		//id=3   LastName:tzq
		
		//测试插入数据
		Student s1=new Student();
		s1.setLastName("IT_BOY");
		s1.setBirth(new Date());
		s1.setSchool("FUDANUNIERSITY");
		studentService.save(s1); 
		System.out.println("数据插入成功!");
	
		
		//注意此种方式必须要有对应的构造器!
		Student stu1 = new Student(null, "AAAA");
		Student stu2 = new Student(null, "BBBB");
		studentService.save(stu1);
		studentService.save(stu2);
	}

}

注意点:

   1. 实体中的注解可以加载属性上,也可以加在getXXX方法上,如果在属性上已经加过了,则spring会自动忽视方法上的注解。

   2.在配置application.xml上的时候莫忘记配置注解驱动,不然之前加的注解将不起作用。

   3.做测试的时候创建对象时必须要有对应的构造方法才可以执行插入操作,利用set方法例外。


    好了,今天的内容就是这了,下节将探讨JPA和SpirngData的集成,这才是重点!恳请大家能给点意见,学习贵在分享,贵在交流,一起进步岂不快哉~  O(∩_∩)O~



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