SpringBoot整合MySQL和Spring Data JP

2019-07-09  本文已影响0人  蜻蜓队长家长

一、搭建SpringBoot项目

请参考SpringBoot分模块项目搭建

二、整合MySQL和JPA

-在pojo中引入MySQL、lombox和JPA,有关lombox不懂的可以参考idea使用lombox

        <!--lombox插件 Project Lombok是一个java库,可以自动插入编辑器并构建工具-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

        <!--JPA Spring Data JPA是更大的Spring Data系列的一部分,可以轻松实现基于JPA的存储库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

-创建com.zhg.demo.pojo.User实体类

package com.zhg.demo.pojo;

import lombok.Getter;
import lombok.Setter;

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

@Getter
@Setter
@Entity
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private String name;
    private String pwd;
    private Integer age;
}

-在dao中引入pojo模块

        <!--添加实体模块-->
        <dependency>
            <groupId>com.zhg</groupId>
            <artifactId>pojo</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

-创建com.zhg.demo.dao.UserDao接口,继承CrudRepository

package com.zhg.demo.dao;

import com.zhg.demo.pojo.User;
import org.springframework.data.repository.CrudRepository;

import java.util.Optional;

public interface UserDao extends CrudRepository<User,Long> {

    Optional<User> findByName(String name);
}

-在dao模块添加com.zhg.jpa.JpaConfiguration类

package com.zhg.demo.jpa;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.zhg.demo.dao")
@EntityScan(basePackages = "com.zhg.demo.pojo")
public class JpaConfiguration {
    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

-在controller模块中添加yml文件(properties文件同理)application.yml(配置文件放在SpringBoot启动类模块中的resources文件夹中)

spring:
  #JPA配置
  jpa:
    database: mysql
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      ddl-auto: update

  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/vptvdb?characterEncoding=utf-8&useSSL=false
    username: root
    password: root


#测试时tomcat的端口,发布时记得注释或删除
server:
  port: 9091

-整合到此就已经完成了,我们可进行测试

三、测试JPA

-在interface模块中引入pojo模块

        <dependency>
            <groupId>com.zhg</groupId>
            <artifactId>pojo</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

-在interface模块添加com.zhg.demo.service.UserService接口

package com.zhg.demo.service;

import com.zhg.demo.pojo.User;

public interface UserService {

    /**
     * 通过用户昵称查找用户信息
     * @param name
     * @return
     */
    User findUserByName(String name);
}

-在service模块中引用interface模块和dao模块

        <!--引入接口模块-->
        <dependency>
            <groupId>com.zhg</groupId>
            <artifactId>interface</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <!--引入数据访问模块-->
        <dependency>
            <groupId>com.zhg</groupId>
            <artifactId>dao</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

-在service模块中添加com.zhg.demo.service.impl.UserServiceImpl类,实现com.zhg.demo.service.UserService接口

package com.zhg.demo.service.impl;

import com.zhg.demo.dao.UserDao;
import com.zhg.demo.pojo.User;
import com.zhg.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User findUserByName(String name) {
        return userDao.findByName(name).orElse(null);
    }
}

-在controller模块中引入service模块和spring-boot-starter-web

        <!--引入接口实现类模块-->
        <dependency>
            <groupId>com.zhg</groupId>
            <artifactId>service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <!--使用Spring MVC构建Web(包括RESTful)应用程序的入门者。使用Tomcat作为默认嵌入式容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

-在controller模块创建com.zhg.demo.controller.UserController类

package com.zhg.demo.controller;

import com.zhg.demo.pojo.User;
import com.zhg.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public User findByName(String name){
        return userService.findUserByName(name);
    }
}

-在controller模块创建com.zhg.demo.SpringBootApplication启动类

package com.zhg.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SbApplication {

    public static void main(String[] args) {
        SpringApplication.run(SbApplication.class, args);
    }
}

-启动并测试(启动前检查数据库是否创建,JPA不需要创表,但是要创建库,表中添加测试数据)


测试接口
上一篇 下一篇

猜你喜欢

热点阅读