springboot+hibernate5+idea2017+maven3

本案例的开发环境:idea2017+maven3+springboot1.5.9+hibernate5

 

一、入门程序(参考spring官网)

第一步:创建一个Maven的web工程

第二步:在pim.xml文件中添加如下配置

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

 第三步:创建一个SampleController类

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

第四步:运行SampleController 类的main程序

第五步:打开浏览器,输入http://localhost:8080/,回车,即可在页面上看到Hello World!

 二、返回jsp视图

第一步:

在application.properties文件中配置如下信息:

# 配置jsp文件的位置,默认位置为:src/main/webapp
spring.mvc.view.prefix=/
# 配置jsp文件的后缀
spring.mvc.view.suffix=.jsp

 表示访问webapp目录下面的以jsp为后缀的视图

第二步:

在pom.xml文件中配置tomcat和jsp的依赖:

<!--添加 tomcat 的支持-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet 依赖 -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- 添加 JSTL 支持 -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
</dependency>

 第三步:

在控制层的类SampleController中添加如下代码:

@RequestMapping("/toJSP")
public String toPage(Model model) {
    System.out.println("3456789");
model.addAttribute("msg","欢迎来到异次元世界");
    return "index";//返回视图
}

第四步:编辑视图

新建一个index.jsp页面

<html>
<body>
<h2>Hello World!</h2>
<h3>${msg}</h3>
</body>
</html>

第五步:运行

运行SampleController 类的main程序

第六步:访问

打开浏览器,输入http://localhost:8080/toJSP,回车,即可在页面上看到信息,但是出现了中文乱码

第七步:修改编码

在application.properties文件中,加入如下编码配置:

#Spring Boot中的乱码和编码问题
spring.http.encoding.force=true

 重新运行main程序,刷新页面,会发现,中文正常显示

 三、扫描包下面的controller

第一步:

在程序入口类上面加注解@SpringBootApplication、@ComponentScan:

 

@Controller//让当前启动入口也成为控制层,如果不想让当前入口也成为控制层,当前程序入口类可以不加Controller注解
@SpringBootApplication
@ComponentScan("com.yunlian")//包名:扫描这个包下面的加了@Controller注解的类及其子包的加了@Controller注解的类,或者加了Service注解等其他组件注解的类
public class SpringBootController {
    
    public static void main(String[] args) throws Exception {
        //程序启动入口,一般该入口文件不写成控制层
        SpringApplication.run(SpringBootController.class, args);
    }
    @RequestMapping("/hello")
    @ResponseBody//返回json数据
    String home() {
        return "Hello World!";
    }
}

  

 第二步:

 

在相应的控制层的类上面加注解@Controller:

package com.yunlian.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/hello")
    @ResponseBody//返回json数据
    String home() {
        return "Hello World    !";
    }
}

 完成上面两步操作即可实现扫描某个包下面的所有的控制层类

 四、注入业务层bean

如,在UserController类中注入UserService。

第一步:创建UserService类

创建一个业务层类UserService.java,并在这个业务类上加上注解@Service:

package com.yunlian.service;

import com.yunlian.entity.User;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    public User getUser(){
        User user = new User();
        user.setId("1");
        user.setUserName("张三");
        user.setPassword("123456789");
        return user;
    }
}

 第二步:业务类bean注入

在控制层中通过@Autowired注解注入业务类bean

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/hello")
    @ResponseBody//返回json数据
    String home() {
        return "Hello World    !";
    }

    @RequestMapping("/get")
    @ResponseBody
    public User getUser() {
       User user = userService.getUser();
       return user;
    }
}

 业务类需要必须在@ComponentScan("com.yunlian")注解所扫描的包中

 五、集成hibernate5

第一步:配置pom.xml文件

配置jpa依赖和MySQL依赖:

 

    <!--jpa dependency-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!--mysql dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.43</version>
    </dependency>

 

第二步:配置application.properties

在application.properties文件中添加数据库连接的相关信息配置

 

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/spring-boot
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10
########################################################
### Java Persistence Api
########################################################
# 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
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
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

 

第三步:创建实体类User

 

package com.yunlian.entity;

import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "user")
public class User implements Serializable {
    private String id;
    private String userName;
    private String password;

    public User() {
    }

    @Id
    public String getId() {
        return id;
    }
    @Column
    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }
    @Column
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }
    @Column
    public void setPassword(String password) {
        this.password = password;
    }

}
 

 

第四步:创建dao层接口UserDao

 

package com.yunlian.dao;

import com.yunlian.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User,String> {
}
 

 

第五步:创建业务层接口UserService

 

package com.yunlian.service;

import com.yunlian.entity.User;

public interface UserService {

    User getUser();

    void save(User user);
}
 

 

第六步:创建业务接口实现类

创建一个业务类UserServiceImpl实现业务接口,并将dao层的bean注入到业务实现类UserServiceImpl中:

 

package com.yunlian.service.impl;

import com.yunlian.dao.UserDao;
import com.yunlian.entity.User;
import com.yunlian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDao userDao;
    @Override
    public User getUser() {
       User user =  userDao.findOne("09e7b25c-12f7-43ea-a553-fb34189fce17");
       return user;
    }

    @Override
    public void save(User user) {
        User u = userDao.save(user);
        return;
    }
}

 

第七步:控制层注入业务bean

在UserController类中注入业务bean:

 

package com.yunlian.controller;

import com.yunlian.entity.User;
import com.yunlian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/hello")
    @ResponseBody//返回json数据
    String home() {
        return "Hello World    !";
    }

    @RequestMapping("/get")
    @ResponseBody
    public User getUser() {
       User user = userService.getUser();
       return user;
    }
    @RequestMapping("/save")
    public String save(Model model){
        User user = new User();
        user.setUserName("李四");
        user.setPassword("123456789");
        user.setId(UUID.randomUUID().toString());
        userService.save(user);
        model.addAttribute("msg","添加数据哇啊");
        return "index";
    }
}
 

 

第八步:程序main入口类的注解配置

找到main程序入口类,在上面加上实体类、持久类的注解@EnableJpaRepositories、@EntityScan

 

package com.yunlian.controller;

import com.yunlian.entity.User;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.*;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller//让当前启动入口也成为控制层,如果不想让当前入口也成为控制层,当前程序入口类可以不加Controller注解
@SpringBootApplication
@ComponentScan("com.yunlian")//包名:扫描这个包下面的加了@Controller注解的类及其子包的加了@Controller注解的类,或者加了Service注解等其他组件注解的类
@EnableJpaRepositories("com.yunlian.dao") // JPA扫描该包路径下的Repositorie
@EntityScan("com.yunlian.entity") // 扫描实体类
public class SpringBootController {

    public static void main(String[] args) throws Exception {
        //程序启动入口,一般该入口文件不写成控制层
        SpringApplication.run(SpringBootController.class, args);
    }
    @RequestMapping("/hello")
    @ResponseBody//返回json数据
    String home() {
        return "Hello World!";
    }

    @RequestMapping("/user")
    @ResponseBody
    public User getUser() {
        User user = new User();
        user.setId("1");
        user.setUserName("张三111");
        user.setPassword("123456789");
        return user;
    }

    @RequestMapping("/toJSP")
    public String toPage(Model model) {
        System.out.println("3456789");
        model.addAttribute("msg","欢迎来到异次元世界");
        return "index";//返回视图
    }
}
 

 

第九步:运行访问

运行main程序,启动好后,打开浏览器根据配置的地址访问即可

 

六、配置springboot日志文件

第一步:配置pom.xml

    <!--spring boot log4j dependency-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j</artifactId>
      <version>1.3.8.RELEASE</version>
    </dependency>

 

 

第二步:添加log4j.properties文件

log4j.properties文件的内容如下:

log4j.rootLogger=info,ServerDailyRollingFile,stdout

log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=D://test/test.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p [%c] - %m%n
log4j.appender.ServerDailyRollingFile.Append=true

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d yyyy-MM-dd HH:mm:ss %p [%c] %m%n

最终的application.properties文件的内容为:

# 配置jsp文件的位置,默认位置为:src/main/webapp
spring.mvc.view.prefix=/
# 配置jsp文件的后缀
spring.mvc.view.suffix=.jsp

#Spring Boot中的乱码和编码问题
spring.http.encoding.force=true

#除了常见的 http encoding,Spring Boot中还可以控制这些编码
#banner.charset
#spring.freemarker.charset
#server.tomcat.uri-encoding
#spring.mail.default-encoding
#spring.messages.encoding
#spring.thymeleaf.encoding

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/spring-boot
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10
########################################################
### Java Persistence Api
########################################################
# 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
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
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

 


 
 

 

 

猜你喜欢

转载自yunlian0621.iteye.com/blog/2404476