新建项目
在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);
}
}