十一、SpringBoot 整合 JPA

1、创建项目

2、配置 application.properties 文件

配置数据库连接以及 hibernate 相关连接:


	spring.datasource.url=jdbc:mysql://localhost:3306/springboot_jpa?serverTimezone=GMT%2B8
	spring.datasource.username=root
	spring.datasource.password=123456
	spring.datasource.driver-class-name=com.mysql.jdbc.Driver
	
	spring.jpa.hibernate.ddl-auto=update
	spring.jpa.show-sql=true

3、创建实体类


	@Entity
	@Table(name = "tbl_user")
	public class User {
	
	    @Id
	    @GeneratedValue(strategy = GenerationType.AUTO)
	    private Integer id;
	
	    @Column(name = "last_name")
	    private String lastName;
	    private String email;
	    private Integer gender;
	
	    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;
	    }
	
	    public Integer getGender() {
	        return gender;
	    }
	
	    public void setGender(Integer gender) {
	        this.gender = gender;
	    }
	}

4、创建 Repository 类


	import org.springframework.data.jpa.repository.JpaRepository;

	public interface UserRepository extends JpaRepository<User,Integer> {
	    User getUserById(Integer id);
	}

5、编写 controller 测试


	@RestController
	public class UserController {
	
	    @Autowired
	    private UserRepository userRepository;
	
	    @GetMapping("/user/{id}")
	    public User getUserById(@PathVariable("id") Integer id) {
	        return userRepository.getUserById(id);
	    }
	
	
	    @GetMapping("/user")
	    public User insertUser(User user) {
	        User user1 = userRepository.save(user);
	        return user1;
	    }
	}

经过以上配置,就可以在 springboot 中使用 jpa 了。

控制台也能打印出 SQL 语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值