SpringDataJPA正向工程

》#千锋逆战#

如果数据库中有表,我们可以逆向工程,如果数据库中没有表,但是我们有实体类,我们可以使用正向工程

pom.xml

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.28</version>
        </dependency>
        <!--
            添加spring-data-jpa的依赖
        -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <!--
            spring-data-jpa依赖于hibernate-entitymanager
        -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
    </dependencies>

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE
user=root
pass=123456

spring-jpa.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:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <context:property-placeholder location="classpath:db.properties"/>

    <context:component-scan base-package="com.qfedu.service"/>
    <context:component-scan base-package="com.qfedu.dao"/>

    <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${url}"/>
        <property name="driverClassName" value="${driver}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${pass}"/>
    </bean>

    <!--
        配置 HibernateJpaVendorAdapter,用来分别设置数据库的方言和是否显示sql语句
    -->
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" id="adapter">
        <!--<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>-->
        <property name="databasePlatform" value="org.hibernate.dialect.MySQL57InnoDBDialect"/>
        <property name="showSql" value="true"/>
    </bean>

    <!--
        配置EntityManagerFactoryBean
    -->
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="emf">
        <property name="dataSource" ref="ds"/>
        <property name="packagesToScan" value="com.qfedu.entity"/>
        <property name="jpaVendorAdapter" ref="adapter"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.format_sql">true</prop>
                <!--
                   使用hibernate.hbm2ddl.auto属性来根据需要动态创建数据库的表结构
                   create:表示启动的时候先drop,再create
                   create-drop: 也表示创建,只不过再系统关闭前执行一下drop
                   update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
                   validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
               -->
                <prop key="hibernate.hbm2ddl.auto">validate</prop>
            </props>
        </property>
    </bean>

    <!--
        配置jpa的事务管理器
    -->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="jtx">
        <property name="entityManagerFactory" ref="emf"/>
    </bean>
    <!--配置事务驱动-->
    <tx:annotation-driven proxy-target-class="false" transaction-manager="jtx"/>
    <jpa:repositories base-package="com.qfedu.dao" entity-manager-factory-ref="emf" transaction-manager-ref="jtx"/>

</beans>

entity

package com.qfedu.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "tbl_emp")
public class Emp {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "eid")
    private int eid;
    /**
     * Column注解的各个属性值说明:
     * name用来指定该属性所对应的列名,默认与属性名一致
     * unique为true代表该属性生成的字段唯一,默认不唯一
     * nullable为false不允许为空,默认运行为空
     * length可以给字段指定长度,默认为255
     */
    @Column(name = "first_name",nullable = false,unique = true,length = 20)
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    private double Salary;
}

dao

package com.qfedu.dao;

import com.qfedu.entity.Emp;
import org.hibernate.boot.model.source.spi.JpaCallbackSource;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
@Repository
public interface IEmpDao extends JpaRepository<Emp, Serializable> {
}

service

package com.qfedu.service;

import com.qfedu.entity.Emp;

public interface IEmpService {
    void saveEmp(Emp emp);
}

service.impl

package com.qfedu.service.impl;

import com.qfedu.dao.IEmpDao;
import com.qfedu.entity.Emp;
import com.qfedu.service.IEmpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EmpServiceImpl implements IEmpService {
    @Resource
    private IEmpDao empDao;

    @Override
    public void saveEmp(Emp emp) {
        empDao.saveAndFlush(emp);
    }
}

test

package com.qfedu.test;

import com.qfedu.entity.Emp;
import com.qfedu.service.IEmpService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-jpa.xml")
public class TestEmp {
    @Resource
    private IEmpService empService;
    @Test
    public void saveEmp() {
        Emp emp = new Emp();
        emp.setFirstName("猪");
        emp.setLastName("八戒");
        emp.setSalary(200000);
        empService.saveEmp(emp);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容