相关引入:
1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2. 实体类
UserLogin.java
package cn.springbooot.SpringBootFrist.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="user")
public class UserLogin {
@Id
@NotNull
@GeneratedValue(strategy=GenerationType.AUTO)
public long id;
@NotNull
@Column(name="password")
public String password;
@NotNull
@Column(name="username")
public String username;
public UserLogin(){};
public UserLogin(String a, String b){
this.username = a;
this.password = b;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
UserLoginDao.java
package cn.springbooot.SpringBootFrist.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import cn.springbooot.SpringBootFrist.model.UserLogin;
/**
* 1、 几种不同的查询方式
* 1. fingById是通过JpaRepository 来进行查询
* 2. 也可以通过自己书写 sql来进行查询
* 3. 可以写在实体类上
*/
public interface UserLoginDao extends JpaRepository<UserLogin,Long>{
public UserLogin findById(Long id);
@Query("select t from UserLogin t where t.username = ?")
public UserLogin findByUsername1(String username);
// 1 是查询方法中参数的顺序
@Query("select t from UserLogin t where t.username = ?1")
public UserLogin findByUsername2(String username);
@Query("select t from UserLogin t where t.username like %:username%")
public UserLogin findByUsername3(@Param("username")String username);
}
出现错误的地方:
nested exception is
javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
引起的原因:是由于实体类名称和数据库中不匹配
如果碰到出入bean失败的地方,要从两个方面着手排查,
1. bean 应该有的注解是否正确添加
2. 包扫描的路径是否正确