Spring Boot 实践1 --创建WEB restful项目,集成jpa

实践背景:基于Spring boot 快速创建web+jpa(mysql)项目

条件:java8,服务器使用springboot 内置tomcat

 (转载请注明来源:cnblogs coder-fang)

 

 

  1.   下载springboot 专用IDE,STS(spring tools),创建项目:
  2. 不要选择其它,直接finish.

  3. 修改POM文件,首先修改 spring-boot-starter-parent版本如下:
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.3.RELEASE</version>
        </parent>

    修改到1.5.3是为了兼容之后我们要实践的spring cloud版本.

  4. 增加web与jpa相关依赖:
            <!-- web -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            
            <!-- jpa -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>            
            </dependency>
  5. 项目包的组织方式如下,使项目入口的Application在最顶层。
  6. 本次实践基于mysql,数据库testdb,数据结构为:

  7. 在com.test.demo.db.entity包下,创建两个表对应的实体(最好使用JPA自动生成工具):

    package com.test.demo.db.entity;
    
    import java.io.Serializable;
    import javax.persistence.*;
    
    import com.fasterxml.jackson.annotation.JsonIgnore;
    
    import java.util.List;
    
    
    /**
     * The persistent class for the department database table.
     * 
     */
    @Entity
    @Table(name="department")
    public class Department implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private int id;
    
        private String name;
    
        //bi-directional many-to-one association to User
        @OneToMany(mappedBy="department")
        @JsonIgnore
        private List<User> users;
    
        public Department() {
        }
    
        public int getId() {
            return this.id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List<User> getUsers() {
            return this.users;
        }
    
        public void setUsers(List<User> users) {
            this.users = users;
        }
    
        public User addUser(User user) {
            getUsers().add(user);
            user.setDepartment(this);
    
            return user;
        }
    
        public User removeUser(User user) {
            getUsers().remove(user);
            user.setDepartment(null);
    
            return user;
        }
    
    }
    View Code
    package com.test.demo.db.entity;
    
    import java.io.Serializable;
    import javax.persistence.*;
    
    
    /**
     * The persistent class for the user database table.
     * 
     */
    @Entity
    @Table(name="user")
    public class User implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private int id;
    
        private String username;
    
        //bi-directional many-to-one association to Department
        @ManyToOne
        @JoinColumn(name="fk_depart")    
        private Department department;
    
        public User() {
        }
    
        public int getId() {
            return this.id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUsername() {
            return this.username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public Department getDepartment() {
            return this.department;
        }
    
        public void setDepartment(Department department) {
            this.department = department;
        }
    
    }
    View Code
  8. 在package com.test.demo.db.repo包中创建repository,只需要继承JpaRepository: 

    package com.test.demo.db.repo;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    import com.test.demo.db.entity.Department;
    
    @Repository
    public interface DepartmentRepository extends  JpaRepository<Department, Integer>
    {
    
    }
    package com.test.demo.db.repo;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    import com.test.demo.db.entity.User;
    
    @Repository
    public interface UserRepository extends JpaRepository<User, Integer>{
    
        User findByUsernameLike(String name);
    }

    通用的CRUD已全部被Spring boot实现(很强大),特定的CRUD只需要在此接口下进行编辑即可(例如 UserRepository下的findByUsernameLike函数),相关的命名规则请自行搜索spring-data-jpa相关资料。

  9. 在application.properties中增加对数据库的访问配置:
    #for db
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8
    spring.datasource.username=test
    spring.datasource.password=test
    spring.jpa.hibernate.ddl-auto=none
    spring.jpa.show-sql=true
  10. 在包 com.test.demo.controller 中增加controller,且可直接注入上述的repository,相关实现springboot已自动为我们完善:
    package com.test.demo.controller;
    
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.test.demo.db.entity.User;
    
    
    @RestController
    public class MainCtrl{    
        
        protected Logger log = LoggerFactory.getLogger(this.getClass());
        
        @Autowired
        protected UserRepository userRepo;
        
        @Autowired 
        protected DepartmentRepository departRepo;
        
        @RequestMapping("user/{name}")
        Object getuser(@PathVariable("name") String name,HttpServletRequest request)
        {        
            log.debug("invoke user by name:"+name);
            request.getSession().setAttribute("user", name);
            User user =userRepo.findByUsernameLike(name+"%"); 
            return user;
        }
        
        @RequestMapping("depart/{id}")
        Object getdepart(@PathVariable("id") Integer id)
        {
            return  departRepo.findOne(id);
        }
        
        
        
        
    }
    View Code
  11. 至此,我们的项目已可以正常运转,YES,就是这么快,使用Run As  Spring boot app,启动应用:
  12. 控制台输出最后几行:
    2017-11-03 15:58:59.347  WARN 10712 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
    2017-11-03 15:58:59.348  INFO 10712 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
    2017-11-03 15:58:59.355  WARN 10712 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
    2017-11-03 15:58:59.356  INFO 10712 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
    2017-11-03 15:58:59.529  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2017-11-03 15:58:59.545  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'environmentManager' has been autodetected for JMX exposure
    2017-11-03 15:58:59.550  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
    2017-11-03 15:58:59.551  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'refreshScope' has been autodetected for JMX exposure
    2017-11-03 15:58:59.556  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'environmentManager': registering with JMX server as MBean [org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager]
    2017-11-03 15:58:59.580  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
    2017-11-03 15:58:59.604  INFO 10712 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=45f223a5,type=ConfigurationPropertiesRebinder]
    2017-11-03 15:59:00.200  INFO 10712 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    2017-11-03 15:59:00.208  INFO 10712 --- [  restartedMain] com.test.demo.SpringmvcTestApplication   : Started SpringmvcTestApplication in 11.76 seconds (JVM running for 13.164)
    View Code
  13. 浏览器中输入localhost:8080/user/zh ,相关界面输出如下:

 

 

   总结:通过上述步骤,迅速搭建WEB应用,SPRING BOOT为我们带的的开发效率是质的变化。

    大家可以搜索springboot相关的filter,listener,也是非常方便的,基本不需要XML配置。

 

 

 

posted @ 2017-11-03 16:09  Coder_fang  阅读(1552)  评论(0编辑  收藏  举报