SpringBoot整合SpringDataJPA操作数据库

创建一个Springboot工程,导入依赖

        <dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-jpaartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<scope>runtimescope>
		dependency>

application.properties属性文件中添加数据库连接信息的配置

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=TheUsername
spring.datasource.password=ThePassword

spring.jpa.hibernate.ddl-auto属性值有
none:MySQL的默认值。没有对数据库结构进行任何更改
update:Hibernate根据给定的实体结构更改数据库
create:每次创建数据库,但在关闭时不删除它
create-drop:创建数据库,并在SessionFactory关闭时删除它

创建一个实体类

package com.liuyong.pojo;

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 name;

    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

@Entity:告诉Hibernate根据这个类建表
@Id:主键字段
@GeneratedValue(strategy = GenerationType.AUTO):主键生成策略为自增

创建一个操作数据库的接口

package com.liuyong.service;

import com.liuyong.pojo.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User,Integer> {
}

spring会自动实现此接口

创建一个Controller接收HTTP请求

package com.liuyong.controller;

import com.liuyong.pojo.User;
import com.liuyong.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping(path="/add")
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }
}

你可能感兴趣的:(SpringBoot)