本文向你展示如何在Spring Boot的Web應(yīng)用中使用Mysq數(shù)據(jù)庫,也充分展示Spring Boot的優(yōu)勢(盡可能少的代碼和配置)收厨。數(shù)據(jù)訪問層我們將使用Spring Data JPA和Hibernate(JPA的實(shí)現(xiàn)之一)。
1.Maven pom.xml文件
在你的項(xiàng)目中增加如下依賴文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
2.屬性配置文件application.properties
在src/main/resources/application.properties中設(shè)置數(shù)據(jù)源和jpa配置优构。
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
全部的配置都在如上的文件中了诵叁,不需要另外的XML配置和Java配置。
上文中的數(shù)據(jù)庫配置俩块,你需要換成你的數(shù)據(jù)庫的地址和用戶名密碼黎休。
hibernate的ddl-auto=update配置表名浓领,數(shù)據(jù)庫的表和列會(huì)自動(dòng)創(chuàng)建(根據(jù)Java實(shí)體的熟悉)玉凯, 這里 可以看到更多得hibernate配置。
3.User實(shí)體
創(chuàng)建一個(gè)User實(shí)體联贩,User包含三個(gè)屬性id,email和name漫仆。User實(shí)體和Mysql數(shù)據(jù)庫的users表相對應(yīng)。
@Entity
@Table(name = "users")
public class User {
// ==============
// PRIVATE FIELDS
// ==============
// An autogenerated id (unique for each user in the db)
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// The user email
@NotNull
private String email;
// The user name
@NotNull
private String name;
// ==============
// PUBLIC METHODS
// ==============
public User() { }
public User(long id) {
this.id = id;
}
// Getter and setter methods
// ...
} // class User
4.User實(shí)體的數(shù)據(jù)訪問層UserDao
本例中UserDao非常簡單泪幌,只需要繼承CrudRespositroy即可盲厌,CrudRespositroy已經(jīng)實(shí)現(xiàn)了save,delete,deleteAll,findOne和findAll.
(比較神奇的時(shí)這些方法其實(shí)CrudRespositroy中其實(shí)并沒有實(shí)現(xiàn),并且通過對dao方法的命名還可以實(shí)現(xiàn)新的方法)
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
public User findByEmail(String email);
}
5.測試的控制器UserController
新建一個(gè)查詢控制器UserController
@Controller
public class UserController {
@RequestMapping("/get-by-email")
@ResponseBody
public String getByEmail(String email) {
String userId;
User user = userDao.findByEmail(email);
if (user != null) {
userId = String.valueOf(user.getId());
return "The user id is: " + userId;
}
return "user " + email + " is not exist.";
}
}
你可以使用瀏覽器訪問url http://127.0.0.1:8080/get-by-email?email=qiyadeng@gmail.com
祸泪,可以獲得用戶的Id(你可以先在Mysql數(shù)據(jù)庫中新增一條記錄)吗浩。