SpringBoot 配置 JPA

14 篇文章 0 订阅
8 篇文章 0 订阅


新建项目

在application.properties配置文件中进行配置(或者application.yaml中配置也行)

spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=UTC

spring.datasource.username=root

spring.datasource.password=root

#是否打印sql

spring.jpa.show-sql=true

#请求访问的时候加个路径前缀

server.servlet.context-path = /SpringBoot

 

实体类

一般在类名上写@Entity、@Table注解,以及主键上写@Id注解

//这里写Entity注解与Table注解

@Entity

@Table(name = "account")

public class Account {

//对主键写ID注解,GeneratedValue为自动递增注解

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

private String loginName;

private String password;

private String nickName;

private int age;

private String location;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getLoginName() {

return loginName;

}

public void setLoginName(String loginName) {

this.loginName = loginName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getNickName() {

return nickName;

}

public void setNickName(String nickName) {

this.nickName = nickName;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getLocation() {

return location;

}

public void setLocation(String location) {

this.location = location;

}

}

 

DAO层

DAO层只要定义接口,并且继承JpaRepository接口就拥有基本的CRUD方法,同时可以写一些自己的特殊方法

public interface AccountDao extends JpaRepository<Account, Integer> {

List<Account> findByIdBetween(int i, int j);

Account findByLoginNameAndPassword(String loginName, String password);

@Query(" select a from Account a where a.id=?1 ")

List<Account> findByParam(Integer id);

}

 

Service 层

@Service

public class AccountService {

@Autowired

AccountDao accountDao;

public void save(Account account) {

accountDao.save(account);

}

public List<Account> list() {

return accountDao.findAll();

}

public List<Account> findByIdBetween(int min, int max) {

return accountDao.findByIdBetween(min, max);

}

public Account findByLoginNameAndPassword(String loginName, String password) {

return accountDao.findByLoginNameAndPassword(loginName, password);

}

public List<Account> findByParam(Integer id) {

return accountDao.findByParam(id);

}

}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值