phper学习springboot-les3-数据库操作

428 阅读2分钟

本节我们会编写注册逻辑,这里就会涉及到数据库的操作了。

本文将使用jpa+mybatis组合对数据库进行操作。

JPA的特点:

  1. JPA对于单表的或者简单的SQL查询非常友好,甚至可以说非常智能。他为你准备好了大量的拿来即用的持久层操作方法。甚至只要写findByName这样一个接口方法,他就能智能的帮你执行根据名称查找实体类对应的表数据,完全不用写SQL。

  2. JPA对于多表关联查询以及动态SQL、自定义SQL等非常不友好。

  3. 如果考虑到动态SQL,写法会更复杂

所以我这里选择,使用二者组合使用。当前正式的企业级开发怎么选择,需要重新考虑。这里只是我做为一个初学者的考虑方案。

关于springboot如何整和mybatis,mybatis官方有介绍。详情可参阅mybatis.org/spring-boot…

依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>	<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

这里引入了jpa、mybatis和mysql-connector依赖。

mybatis-spring-boot-starter 为我们做了什么?

MyBatis-Spring-Boot-Starter will:

  1. 自动检测sprigboot中存在的 DataSource
  2. 创建并注册SqlSessionFactory实例, passing that DataSource as an input using the SqlSessionFactoryBean
  3. Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
  4. 自动扫描你的 mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your bean

配置

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

spring.jpa.hibernate.ddl-auto 这个配置可选项有 none, update, create, or create-drop. 具体可以参看 docs.jboss.org/hibernate/o….

  • none: 对于mysql的默认配置。不会对数据库结构有影响

  • update: Hibernate 会根据你的entity定义改变数据库结构

  • create: 每次都会创建数据库,但不会在断开服务时删除

  • create-drop: 创建并会删除 当SessionFactory 关闭.

Hibernate 将会自动将entity映射到数据库的table上去。

定义entity

import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String email;
    private Calendar createTime;
    private Calendar modifyTime;

    public User() {
        Calendar createCalendar = Calendar.getInstance();
        this.createTime = createCalendar;
    }

    public Integer getId() {
        return id;
    }

    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 Calendar getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Calendar createTime) {
        this.createTime = createTime;
    }

    public Calendar getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Calendar modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

定义mapper


import com.vison.learnMall.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {

    @Select("select username,email from user where username = #{username}")
    User findByUsername(String username);

}

对于复杂的sql或动态sql可以使用mybatis进行作业。

定义repositoty


import com.vison.learnMall.entity.User;
import org.springframework.data.repository.CrudRepository;


public interface UserRepository extends CrudRepository<User, Integer> {

}

对于一般性质的curd其实可以走jpa确实很方便。

定义response

一般而言,一个项目或一个公司的api返回结构都是约定好的。甚至有写返回码都是固定的。所以可以定义好返回的数据结构。

import java.util.ArrayList;
import java.util.List;


public class Response {

    private int ret;
    private String msg;
    private Object data;

    public Response(int ret, String msg, Object data) {
        this.ret = ret;
        this.msg = msg;
        this.data = data;
    }

    public Response(int ret, String msg) {
        this.ret = ret;
        this.msg = msg;
        List list = new ArrayList();
        this.data = list;
    }

    public void setRet(int ret) {
        this.ret = ret;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public int getRet() {
        return ret;
    }

    public String getMsg() {
        return msg;
    }

    public Object getData() {
        return data;
    }

}

获取自定义配置

 
@RestController
@PropertySource(value = "classpath:app.properties")
public class UserController extends BaseController {

    @Value("${app.security.salt}")
    private String salt;

我们定义好配置文件后可以通过@Value和@PropertySource获取自定义的配置

处理注册逻辑

@RequestMapping(path = "/user/handRegister", method = RequestMethod.POST)
    public Response doRegister(HttpServletRequest request) {
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String pwd = request.getParameter("pwd");
        String confirmPwd = request.getParameter("confirmPwd");
        if (username == null || email == null || pwd == null || confirmPwd == null) {
            return new Response(1, "参数错误");
        }

        if (!pwd.equals(confirmPwd)) {
            return new Response(1, "2次密码输入不正确");
        }

        if (this.userMapper.findByUsername(username) == null) {
            User user = new User();
            user.setEmail(email);
            user.setUsername(username);
            user.setPassword(Security.encrypt(pwd, this.salt));
            if (userRepository.save(user) == null) {
                return new Response(1, "插入数据失败");
            }
        }

        return new Response(2, "该账户已注册过");
    }

通过HttpServletRequest可以获取请求提交的数据。

总结

本节涉及的知识点有点多:

  1. JPA的使用,定义entity和使用repositoty进行简单的curd
  2. 引入Mybatis,对于复杂或动态sql进行处理
  3. 定义reponse数据结构,统一接口返回结构
  4. 通过@Value和@PropertySource优雅的方式获取自定义配置
  5. 通过HttpServletRequest获取http请求参数