package com.example.demo.entity;
import javax.persistence.*;
/*使用jpa注解配置映射关系*/
/*告诉jpa这是一个实体类和(数据表映射的类)*/
@Entity
@Table(name = "tal_user")
public class User {
@Id /*这是主键*/
@GeneratedValue(strategy = GenerationType.IDENTITY) /*主键自增*/
private Integer id;
@Column(name = "lastName",length = 50)/*这是和数据表对应的一个列*/
private String lastName;
@Column /*省略就代表默认属性名就是列名*/
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/*继承jpaRepository来完成对数据库的操作 参数是实体类型和实体类中的Id类型*/
public interface UserRepository extends JpaRepository<User, Integer> {
}
package com.example.demo.Controller;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user/{id}")
public List<User> getUser(@PathVariable("id") Integer id){
User user = userRepository.getOne(id);
final List<User> users = userRepository.findAll();
return users;
}
@GetMapping("/user")
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}
}
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
# 更新或者创建表结构
ddl-auto: update
# 控制台显示sql
show-sql: true
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>8.0.12</scope>
</dependency>