SpringBoot整合 Mybatis+freemarker

使用SpringBoot整合MyBatis+freemarker实现一个web项目的简单流程以及配置:

1. 在pom.xml中导入相关依赖:

<dependencies>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.bootgroupId>
			<artifactId>mybatis-spring-boot-starterartifactId>
			<version>1.3.2version>
		dependency>
		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<scope>runtimescope>
		dependency>
		
		<dependency>
			<groupId>tk.mybatisgroupId>
			<artifactId>mapper-spring-boot-starterartifactId>
			<version>2.1.5version>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-freemarkerartifactId>
		dependency>
	dependencies>

2. 在springboot中配置全局文件application.properties中的相关信息:

数据编码格式,数据库连接等等信息,这里只贴了需要用到的

#设置spring-boot 编码格式
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8

#数据库连接配置:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#打印日志所需配置
logging.level.com.example.demo.dao=debug

#freemarker文件默认后缀名改成html
spring.freemarker.suffix=.html

3. 创建实体类:

public class User {
	private Integer id;
	private String name;
	getset方法
}

4. Mapper层文件(启动类中有了扫描,这里可以不用注解):

//@MapperScan
public interface UserMapper extends Mapper<User>{
	/*@select("select * from user")
	public List selectAll();*/
}

5. controller层:

这里用的普通controller,springboot中controller中默认都是异步请求,可以使用@RestController注解,使用@Value("${name}")来获取值

@Controller
public class UserController {
	@Autowired
	UserMapper usermapper;
	@RequestMapping("show")
	public String show(Map<String, Object> map){
		map.put("userlist",usermapper.selectAll());
		return "index";
	}
}

6. 启动类中加上扫描mapper层的注解:

@MapperScan(basePackages="com.demo.mapper")
@SpringBootApplication
public class SpringBoot011Application {
	public static void main(String[] args) {
		SpringApplication.run(SpringBoot011Application.class, args);
	}

}

7. 在html页面显示查询结果:

<body>
	<#list userlist as ul>
		${ul.id}--${ul.name}
	#list>
body>

你可能感兴趣的:(开发,Springboot,mybatis)