springboot-集成 spirng-data-jpa
缘起
由于平时要做一些小项目, 用 mybatis 比较麻烦, 所以打算用 jpa,于是乎。。。。
1 创建springboot 项目,并且导入依赖
<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>
2 配置数据源,在 application.yml 文件配置:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update # 第一次建表create 后面用update
show-sql: true
3 创建实体类
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id ;
@Column
private String userName;
@Column
private String passWord;
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
}
5 Controller
/**
* @Author: huangwenjun
* @Description:
* @Date: Created in 9:50 2018/5/11
**/
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserDao userDao;
@PostMapping("add")
public User add(User user) {
return userDao.save(user);
}
@PostMapping("delete")
public void delete(Integer id) {
userDao.deleteById(id);
}
@PostMapping("find")
public User find(Integer id) {
Optional<User> optionalUser = userDao.findById(id);
return optionalUser.get();
}
}
好了 到这里完成了 , 这个项目启动的时候会自动建表。 不用不用我们去写 sql, 对于小项目 还是建议用 jpa 简单粗暴。