Maven Spring Boot mybatis Demo

发布时间:2017-11-14浏览:

核心提示:MyEclipse Maven Spring Boot mybatis freemarker 配置实例DEMO

MyEclipse Maven Spring Boot mybatis freemarker 配置实例DEMO

1.首先在Myeclipse中新建一个Maven Project项目;本实例中,读取Mysql数据库的数据,在 freemarker模板中显示出来,模板文件在,src/main/resources/templates下的user目录的list.ftl

模板文件代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<table>
   <tr>
       <th>id</th><th>用户名</th><th>密码</th><th>邮箱</th>
   </tr>
   <#list userList as user>
   <tr>
       <td>${user.id}</td> <td>${user.username}</td><td>${user.password}</td><td>${user.email}</td>
   </tr>
   </#list>
  </table>
</body>
</html>

src/main/resources/mybatis文件夹下UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lm.dao.UserMapper">
  <select id="findAll" resultType="com.lm.model.User"  parameterType="java.lang.String">
    select id, username,password,email from t_user
  </select>
</mapper>

 

2.配置文件application.properties

#datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# FREEMARKER (FreeMarkerAutoConfiguration)
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=true
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true
spring.freemarker.order=1
#server
server.port=8081         

说明一下,这个文件主要是配置datasource  数据源,和freemarker模板的配置,server.port配置内置服务器的端口8080,(这里测试中不需要外部的服务器,配置好,运行直接就使用Spring Boot内置的服务器测试,很方便)

 

Spring Boot特点

编辑
1. 创建独立的Spring应用程序
2. 嵌入的Tomcat,无需部署WAR文件
3. 简化Maven配置
4. 自动配置Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置
6. 绝对没有代码生成和对XML没有要求配置

 

 

3.pom.xml  整个项目的配置文件如下:

<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>com.lm.spring-boot</groupId>
<artifactId>spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--视图采用freemarker渲染 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<!-- 指定最终生成jar包的文件名-->
<finalName>spring-boot</finalName>
</build>
</project>


4.项目的application/application.java 也是程序的入口部分,


package com.lm.application;


import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


@EnableAutoConfiguration  
@SpringBootApplication
@ComponentScan(basePackages={"com.lm"})//指定spring要扫描的包
@MapperScan("com.lm.dao")//指定mapper文件所在的包
public class Application{

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

//创建数据源
@Bean  
    @ConfigurationProperties(prefix = "spring.datasource")//ָ指定数据源的前缀
    public DataSource dataSource() {  
        return new DataSource();  
    }

//创建SqlSessionFactory
@Bean  
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {  
  
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();  
        sqlSessionFactoryBean.setDataSource(dataSource());  
  
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();  
  
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));//指定mapper文件所在目录  
  
        return sqlSessionFactoryBean.getObject();  
    }  

//创建事务管理器
@Bean  
    public PlatformTransactionManager transactionManager() {  
        return new DataSourceTransactionManager(dataSource());  
    }
}


5.controller/UserController.java 控制类

package com.lm.controller;


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.lm.model.User;
import com.lm.service.UserService;


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

@Autowired
private UserService userService;

    @RequestMapping("/list")
    public String list(ModelMap map){
    List<User> userList=userService.findAll();
    map.addAttribute("userList", userList);
    return "/user/list";
    }
}


6.dao/UserMapper.java         mybatis  mapper文件所在的包

package com.lm.dao;


import java.util.List;
import com.lm.model.User;


public interface UserMapper {


List<User> findAll();


}


7.model/User.java 模型类

package com.lm.model;


public class User {
private Integer id;
private String username;
private String password;
private String email;


public Integer getId() {
return id;
}


public void setId(Integer id) {
this.id = id;
}


public String getUsername() {
return username;
}


public String getEmail() {
return email;
}


public void setEmail(String email) {
this.email = email;
}


public void setUsername(String username) {
this.username = username;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}


}


8.service/UserService.java


package com.lm.service;


import java.util.List;


import com.lm.model.User;


public interface UserService {


List<User> findAll();


}


9.sevice/impl/UserServiceImpl.java

package com.lm.service.impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.lm.dao.UserMapper;
import com.lm.model.User;
import com.lm.service.UserService;


@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserMapper userMapper;

@Override
public List<User> findAll() {
return userMapper.findAll();
}

}

10.项目文件如下图所示:




11.至此spring-boot框架已搭建完成,然后在Application.java中run as >java application此时在控制台会看到如下日志输出:




12.打开浏览器在地址栏输入http://localhost:8081/user/list便可以看到以下效果:

(注意我们在application.properties 中设置了server.port=8081),你也可以设置其他(80,8080)端口,只要不冲突


 


前一篇:定做程序设计
后一篇:MyEclipse +Maven+Spring+Spring MVC +Mybatis+bootstrap+Mysql信息(增删改查分页)实战
分享到: