Spring-Data-Jpa配合MySQL实现简单的增、删、查、改

  1. 创建Maven项目
  2. 配置pom.xml仓库文件
<dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>1.11.3.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-entitymanagerartifactId>
            <version>5.2.5.Finalversion>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.28version>
        dependency>
             
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>4.3.6.RELEASEversion>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.41version>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.6.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
        <finalName>SpringDataJpa1finalName>
    build>
  1. spring-data.xml配置,这是一个spring的配置文件,包括加载数据源、事物驱动、注解扫描等。
?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:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    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-4.3.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <context:component-scan base-package="com.web.dao.impl"/>

    <context:component-scan base-package="com.web.service.impl"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///jpa"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    bean>
    
    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="showSql" value="true"/>
        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
    bean>
    
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="packagesToScan" value="com.web.po"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.format_sql">trueprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
    bean>
    
    <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
    bean>
    
    <tx:annotation-driven proxy-target-class="false" transaction-manager="jpaTransactionManager"/>
    
    <jpa:repositories base-package="com.web.dao"
         entity-manager-factory-ref="emf"
         transaction-manager-ref="jpaTransactionManager"/>
beans>
  1. 这里的是Jpa的原生实现,下一张会采用接口(JpaRepository)的方法。

UserDao.java接口

![dao层](http://img.blog.csdn.net/20170531205841343?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmFpZHVfMzQ4MzIwMjY=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
//查找全部
    List findAll();
    //增加用户
    void addUser(User user);
    //修改用户
    void updateUser(User user);
    //删除用户
    int deleteUser(String userId);
    //根据id来查找
    User findById(String userId);
    //登录
    User loginUser(String name,String pass);

    void removeUser(User user);

dao层的实现类

//获取上下文实体持久管理器
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List findAll() {
        return (List) entityManager.createQuery("from User").getResultList();
    }

    @Override
    public void addUser(User user) {
        entityManager.persist(user);
        entityManager.flush();
    }

    @Override
    public void updateUser(User user) {
        //entityManager.refresh(user);
        entityManager.merge(user);
        entityManager.flush();
    }

    @Override
    public int deleteUser(String userId) {
        int rows = entityManager.createQuery("delete from User u where u.userId=?").setParameter(0, userId)
        .executeUpdate();
        return rows;
    }

    @Override
    public User findById(String userId) {

        return entityManager.find(User.class, userId);
    }

    @Override
    public User loginUser(String name, String pass) {
        User singleResult = (User) entityManager.createQuery("select u from User u where u.userName=? "
                + "and passWord=?").setParameter(0, name)
        .setParameter(1, pass).getSingleResult();
        return singleResult;
    }

    @Override
    public void removeUser(User user) {
        User user2 = entityManager.merge(user);
        entityManager.remove(user2);
        entityManager.flush();
    }

service接口和实现类的注解都很简单,就不用介绍了
Spring-Data-Jpa配合MySQL实现简单的增、删、查、改_第1张图片

  1. 测试类采用的spring自带的测试
![测试类]
(http://img.blog.csdn.net/20170531212620766?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmFpZHVfMzQ4MzIwMjY=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

6、上面方法比较复杂,我们可以直接在dao层继承JpaRepository仓库,然后在dao层不需要写任何代码,除了特殊的

7、在我们的的service的实现类里面直接可以调用我们仓库里的方法,和上面的serviceImpl一样,里面包括简单的增加、删除、修改、查看和分页、分类等。

你可能感兴趣的:(web基础,web框架)