Spring Data JPA 入门例子

来源:互联网 发布:mysql in用法 编辑:程序博客网 时间:2024/05/16 18:09

本例子代码下载地址:http://download.csdn.net/detail/wu_boy/9132675

1、新建一个Maven Web项目,如下图所示
项目结构图
2、Maven引用如下图所示
Maven引用图
3、实体类User及dao、service代码分别如下
User类

@Entity(name="security_user")public class User implements Serializable{    private static final long serialVersionUID = 2988832907988887034L;    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    private Integer id;    private String userName;//用户名    private String password;//密码    //此处省略了get/set方法,请自行补上

UserDao接口

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.stereotype.Repository;@Repositorypublic interface UserDao extends PagingAndSortingRepository<User, Integer>, JpaSpecificationExecutor<User>{    User findByUserName(String userName);}

UserService接口

public interface UserService{    User findByUserName(String userName);    User save(User o);}

UserServiceImpl类

import javax.annotation.Resource;import javax.transaction.Transactional;import org.springframework.stereotype.Service;@Service@Transactionalpublic class UserServiceImpl implements UserService{    @Resource    protected UserDao userDao;    @Override    public User findByUserName(String userName) {        return userDao.findByUserName(userName);    }    @Override    public User save(User o) {        return userDao.save(o);    }}

applicationContext.xml配置文件如下

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:aop="http://www.springframework.org/schema/aop"    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"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop.xsd     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.xsd">    <description>Spring公共配置文件 </description>    <context:component-scan base-package="com.wu.project" />    <context:annotation-config/>    <context:property-placeholder location="classpath:application.properties" />    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />    </bean>    <!-- 定义实体管理器工厂Jpa配置 -->    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        <property name="dataSource" ref="dataSource"/>        <!-- 指定Jpa持久化实现厂商类,这里使用Hibernate -->        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>        <!-- 指定Entity实体类包路径 -->        <property name="packagesToScan" >            <array><value>com.wu.project</value></array>        </property>        <!-- 指定JPA属性;如Hibernate中指定是否显示SQL的是否显示、方言等 -->        <property name="jpaProperties">            <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>                <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>                <prop key="hibernate.show_sql">true</prop>                <prop key="hibernate.format_sql">true</prop>            </props>        </property>    </bean>    <!-- 启用扫描并自动创建代理的功能  -->    <jpa:repositories base-package="com.wu.project"  transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>    <!-- Hibernate对Jpa的实现 -->    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>    <!-- Jpa 事务管理器  -->    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">        <property name="entityManagerFactory" ref="entityManagerFactory"/>    </bean>    <!-- 开启注解事务 -->    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /></beans>

数据库配置文件application.properties如下

jdbc.url=jdbc:mysql://127.0.0.1:3306/projectjdbc.username=rootjdbc.password=mysql

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"     xmlns:web="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_3_0.xsd"     id="WebApp_ID" version="3.0">    <display-name>project</display-name>    <!-- Spring配置文件开始  -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- Spring配置文件结束 -->    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>

建表语句如下

DROP TABLE IF EXISTS security_user;CREATE TABLE security_user (  id INT AUTO_INCREMENT PRIMARY KEY,  user_name VARCHAR(32) COMMENT '用户名',  password VARCHAR(32) COMMENT '密码') ENGINE =InnoDB DEFAULT CHARSET =utf8 COMMENT ='用户表';

ServiceTest测试类如下

import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.wu.project.user.User;import com.wu.project.user.UserService;public class ServiceTest {    private static ApplicationContext act = null;    @BeforeClass    public static void setUpBeforeClass() throws Exception {        act = new ClassPathXmlApplicationContext("applicationContext.xml");    }    @Test    public void test() throws Exception{        UserService service = (UserService)act.getBean("userServiceImpl");        User o = new User();        o.setUserName("admin");        o.setPassword("123456");        service.save(o);        System.out.println(service.findByUserName("admin"));    }}

本例子代码下载地址:http://download.csdn.net/detail/wu_boy/9132675

参考资料:1、Spring Data Jpa 详解 (配置篇)
2、使用 Spring Data JPA 简化 JPA 开发

0 0