在IDEA中使用spring-boot,mySql,JPA

来源:互联网 发布:南音吉他小屋 淘宝 编辑:程序博客网 时间:2024/06/06 20:19

本篇介绍如何用最少的代码和配置在Spring Boot web application中使用Mysql,数据层使用Spring Data JPA

1.使用ItelliJ IDEA创建spring initializr工程 

2.在pom.xml中添加依赖

<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>   <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>      <scope>test</scope>   </dependency></dependencies>
3.在resources下添加application.properties 添加配置信息
spring.datasource.url = jdbc:mysql://localhost:3306/testspring.datasource.username = rootspring.datasource.password = rootspring.datasource.driverClassName = com.mysql.jdbc.Driver# Specify the DBMSspring.jpa.database = MYSQL# 在控制台显示自动生成的sql语句# Show or not log for each sql queryspring.jpa.show-sql = true# 项目启动的时候Hibernate会自动创建表和更新表# Hibernate ddl auto (create, create-drop, update)spring.jpa.hibernate.ddl-auto = update# 命名策略# Naming strategyspring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy# RDBMS 方言, 这里选用MySQL5Dialect# stripped before adding them to the entity manager)spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
这里的数据库连接用自己的数据库
4.创建一个实体类
@Entity标注这个类为JPA的一个实体 
@Table来指定在数据库中的表名
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
标注主键id自增 
package com.springboot1;import javax.persistence.*;import javax.validation.constraints.NotNull;/** * Created by 340092 on 2017/11/20. */@Entity@Table(name = "users")public class User {    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    private long id;    // The user email    @NotNull    private String email;    // The user name    @NotNull    private String name;    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
这个时候用spring-boot:run启动项目就可以看到这个表已经在数据库中生成了
5.User实体的数据访问层UserDao(
本例中UserDao非常简单,只需要继承CrudRespositroy即可,CrudRespositroy已经实现了save,delete,deleteAll,findOne和findAll
 注意,只要接口,不需要任何实现)
package com.springboot1;import org.springframework.data.repository.CrudRepository;import org.springframework.transaction.annotation.Transactional;@Transactionalpublic interface UserDao  extends CrudRepository<User, Long> {       public User findByEmail(String email);}

紧紧以上这些代码和配置就可以访问数据库了,非常的简单,下面通过控制器来测试一下 
package com.springboot1;/** * Created by 340092 on 2017/11/20. */import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * @RestController 相当于@ControllerRequestBody * Created by 340092 on 2017/11/16. */@RestControllerpublic class HelloController {    @Autowired    UserDao userDao;    /**     * GET /create  --> Create a new user and save it in the database.     */    @RequestMapping(value = "/create",produces="text/html;charset=UTF-8",method = RequestMethod.GET)    public String create(String email, String name) {        String userId = "";        try {            User user = new User(email, name);            userDao.save(user);            userId = String.valueOf(user.getId());        }        catch (Exception ex) {            return "Error creating the user: " + ex.toString();        }        return "User succesfully created with id = " + userId;    }}
访问http://localhost:8080/create?email=qq.com&name=张三即可.

阅读全文
0 0