1,pom引入:java
<!-- 數據庫 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>mysql
2,application.properties的配置:spring
#數據庫鏈接
spring.datasource.url=jdbc:mysql://localhost:3306/test_fun?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=hitwh
spring.datasource.driver-class-name=com.mysql.jdbc.Driversql
# JPA
## 若是 實體對應的表不存在,會自動建立
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true數據庫
3,bean建立:app
@Entity
public class User {spring-boot
@Id
@GeneratedValue
private Integer id;url
@Column
private String name;
@Column
private int age;.net
}hibernate
4,dao建立:
public interface UserDao extends JpaRepository<User, Integer> {
@Query(value = "select u from User u where u.name=? ")
List<User> findByUserName(String userName);
}
特別注意:@Query中的sql語句 可不是 原生的sql,User對應的是Bean的名稱,而不是 數據庫表名
5,使用dao:
@Autowired private UserDao dao; @Test public void query() { List<User> list = dao.findByUserName("dd"); System.out.println(list.toString()); }