码迷,mamicode.com
首页 > 编程语言 > 详细

第一个小demo: spring boot + mybatis + thymeleaf

时间:2018-08-14 21:00:19      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:关闭   blank   autowire   server   运行   nod   pre   website   variable   

整体项目结构

技术分享图片

 

1. 创建一个Maven web项目

技术分享图片

2. 引入相关依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cmbt</groupId>
  <artifactId>springbootdemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springbootdemo Maven Webapp</name>
  <!-- FIXME change it to the project‘s website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath />
  </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--启动时启动内置tomcat -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- MySql驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.21</version>
    </dependency>
    <!-- 热部署 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
      <scope>true</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>springbootdemo</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <!-- 没有该配置,devtools 不生效 -->
          <fork>true</fork>
        </configuration>
      </plugin>
    </plugins>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3. 新建一个 application.properties 文件

server.port=8000
#thymeleaf start
spring.thymeleaf.prefix=classpath:/templates/  
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面(pom已经配了热部署插件,所以不用打开了)
#spring.thymeleaf.cache=false
#thymeleaf end


#数据库配置
spring.datasource.url=jdbc:mysql://数据库ip:3306/mydb?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4. 创建数据库及表

CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET latin1 */;

CREATE TABLE `t_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `student` tinyint(1) DEFAULT NULL,
  `sex` enum(‘MALE‘,‘FEMALE‘,‘SECRET‘) DEFAULT ‘SECRET‘,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

5. 建一个controller

@Controller
public class IndexController {
    private final static Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private IUserService userService;

    @RequestMapping("/helloworld")
    public String helloworld() {
        return "helloworld";
    }

    @ResponseBody //加了此注解就不会通过模板返回
    @GetMapping("/getUser/{userId}")
    public User getUser(@PathVariable Integer userId) {
        User user = userService.getUser(userId);
        return user;
    }

    @GetMapping(value = "/hello")
    public String hello(Model model) {
        logger.info("logback 访问hello");
        logger.error("logback 访问hello");

        String name = "hello aaa";
        model.addAttribute("name", name);
        return "hello";
    }
}

6. mapper文件

public interface UserMapper {

    @Select("SELECT * FROM t_user")
    @Results({
            @Result(property = "userId",  column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "password", column = "password"),
            @Result(property = "phone", column = "phone"),
            @Result(property = "student", column = "student", javaType = boolean.class),
            @Result(property = "sex", column = "sex", javaType = Sex.class)
    })
    List<User> getList();


    @Select("SELECT * FROM t_user WHERE user_id = #{id}")
    @Results({
            @Result(property = "userId",  column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "password", column = "password"),
            @Result(property = "phone", column = "phone"),
            @Result(property = "student", column = "student", javaType = boolean.class),
            @Result(property = "sex", column = "sex", javaType = Sex.class)
    })
    User getUser(Integer id);

    @Insert("INSERT INTO t_user(user_name, password, phone, student, sex) VALUES(#{userName}, #{password}, #{phone}, #{student}, #{sex})")
    void insert(User user);

    @Update("UPDATE t_user SET user_name=#{userName},password=#{password} WHERE user_id =#{userId}")
    void update(User user);

    @Delete("DELETE FROM t_user WHERE user_id =#{id}")
    void delete(Long id);
}

7. service文件

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userDao;
    
    public List<User> getList() {
        return userDao.getList();
    }

    public User getUser(Integer id) {
        return userDao.getUser(id);
    }

    public void insert(User user){
        userDao.insert(user);
    }

    public void update(User user){
        userDao.update(user);
    }

    public void delete(Long id){
        userDao.delete(id);
    }

}

8. 打war包,部署到tomcat: mvn clean package

9. 启动tomcat,运行效果

技术分享图片

技术分享图片

 

 代码下载地址 https://github.com/coder-cmbt/demo-spring-boot-mybatis-thymeleaf 

第一个小demo: spring boot + mybatis + thymeleaf

标签:关闭   blank   autowire   server   运行   nod   pre   website   variable   

原文地址:https://www.cnblogs.com/cmbt/p/9477487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!