1.依赖
2.新增model
3.新增接口
4.测试
一 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二 新增model
package com.ligy.springbootstudyjpa.model; import javax.persistence.*; @Entity @Table(name = "account") public class Account { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "username") private String username; @Column(name = "password") 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; } @Override public String toString() { return "Account{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
三 新增接口
package com.ligy.springbootstudyjpa.repository; import com.ligy.springbootstudyjpa.model.Account; import org.springframework.data.jpa.repository.JpaRepository; public interface AccountRepository extends JpaRepository<Account, Integer> { }
四 测试
package com.ligy.springbootstudyjpa; import com.ligy.springbootstudyjpa.model.Account; import com.ligy.springbootstudyjpa.repository.AccountRepository; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; @SpringBootTest public class JpaTest { @Resource AccountRepository accountRepository; @Test void test4() { Account account = accountRepository.findById(1).get(); System.out.println("查询成功:" + account); account.setPassword("11111111"); accountRepository.save(account); System.out.println("更新成功:" + account); } @Test void test3() { List<Account> all = accountRepository.findAll(); System.out.println("查询成功:" + all); } @Test void test2() { Account account = new Account(); account.setId(3); accountRepository.delete(account); System.out.println("删除成功:"); } @Test void test1() { Account account = new Account(); account.setUsername("tom"); account.setPassword("123456"); Account save = accountRepository.save(account); System.out.println("插入成功:" + save); } }