1. 程式人生 > >使用spring data jpa簡化dao層編寫

使用spring data jpa簡化dao層編寫

一、新增maven依賴:

...
<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>jcl-over-slf4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
...

二、增加配置檔案(applicationcontext.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
	<!-- 使註解生效 -->
	<context:annotation-config />

	<!-- 配置資料來源 -->
<!-- p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" 
        p:driverClassName="com.p6spy.engine.spy.P6SpyDriver"
        p:url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test2"
        p:username="sa"
        p:password="csc123456"/>
        
	<!-- jpa實體工廠配置 -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		p:dataSource-ref="dataSource"
		p:sharedCacheMode="ENABLE_SELECTIVE"
		p:validationMode="NONE"
		p:packagesToScan="com.ldy.entities">
		<property name="jpaPropertyMap">
			<props>
				<prop key="javax.persistence.schema-generation.database.action">none</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" 
				p:databasePlatform="org.hibernate.dialect.SQLServer2008Dialect" />
		</property>
	</bean>
	
	<jpa:repositories base-package="com.ldy.repositories" transaction-manager-ref="transactionManager"
		 entity-manager-factory-ref="entityManagerFactory"/>
	
	<!-- Jpa 事務管理器  -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" 
		p:entityManagerFactory-ref="entityManagerFactory"/>	 
	
	<!-- 開啟註解事務 -->
	<tx:annotation-driven />
</beans>

三、編寫域模型

<pre name="code" class="java">package com.ldy.entities;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="lsuser")
public class User implements Serializable {
	private String userID;
	private String roleID;
	private String userName;
	private String password;
	private String email;
	private String ceilPhone;
	private Date createTime;
	private String createUser;
	private Date modifyTime;
	private String modifyUser;
	@Id
	//@GeneratedValue(strategy = GenerationType.IDENTITY)
	@GeneratedValue(generator="custom_uuid")
	@GenericGenerator(name="custom_uuid",strategy="uuid2")
	public String getUserID() {
		return userID;
	}
	public void setUserID(String userID) {
		this.userID = userID;
	}
	public String getRoleID() {
		return roleID;
	}
	public void setRoleID(String roleID) {
		this.roleID = roleID;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getCeilPhone() {
		return ceilPhone;
	}
	public void setCeilPhone(String ceilPhone) {
		this.ceilPhone = ceilPhone;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public String getCreateUser() {
		return createUser;
	}
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}
	public Date getModifyTime() {
		return modifyTime;
	}
	public void setModifyTime(Date modifyTime) {
		this.modifyTime = modifyTime;
	}
	public String getModifyUser() {
		return modifyUser;
	}
	public void setModifyUser(String modifyUser) {
		this.modifyUser = modifyUser;
	}
	
}

四、宣告倉庫介面

package com.ldy.repositories;


import org.springframework.data.repository.CrudRepository;


import com.ldy.entities.User;
public interface UserRepositories extends CrudRepository<User,String>{


}

五、編寫測試

package com.ldy.springdata.runtime;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.inject.Inject;

import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ldy.entities.User;
import com.ldy.repositories.UserRepositories;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/config/applicationContext.xml")
public class DataSourceTest {
	@Inject
    private ApplicationContext applicationContext;
	@Inject UserRepositories userRepo;
	@Test
	public void testUserRepositoies(){
		User user = new User();
		user.setCeilPhone("12222323421");
		user.setEmail("[email protected]");
		System.out.println("userRepo.save(user):"+userRepo.save(user));
	}
}