修改pom.xml
1 | <dependency> |
修改application
1 | ######################################################## |
测试
新建一个类User.java;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by LM on 2017/8/6.
*/
public class User{
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
重新运行,在navicat中查看发现多了一个user表
深入操作
建表
ddl-auto:create会新建一个表如果你之前有这个表会被删掉
User.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by LM on 2017/8/6.
*/
public class User{
private long id;
private String name;
private Integer age;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
运行,多了age一列
ddl-auto: update 不会删掉,会保留
ddl-auto: create-drop 应用停下来删掉表
ddl-auto: none 什么都不做
validate:验证是否一致,不一致报错
写API操作数据库
get接口读取user表
新建一个类:UserController.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = "users")
public List<User> userList(){
return userRepository.findAll();
}
}
新建一个Interface :UserRepository1
2
3
4
5
6
7package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer>{
}
重启:http://127.0.0.1:8080/users
返回1
2
3
4
5
6
7[
{
"id": 1,
"name": "yinxs",
"age": 12
}
]
新增一条user信息
在UserController.java中添加
1 |
|
重启:http://127.0.0.1:8080/users
name:yin
age:16
返回1
2
3
4
5{
"id": 3,
"name": "yin",
"age": 16
}
错误处理
1 | org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.example.demo.User. Expected: class java.lang.Long, got class java.lang.Integer |
原因:id的类型不对
1 | could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested excepti... |
原因:数据库被修改