Spring Boot整合SSM三大框架(spring+springmvc+mybatis)的步骤。
1. 建立数据库表格
2. 建立实体 验证@Validated可以在属性上进行非空什么的
3. 建立接口:注意唯一和MyBatis不同的是,这个接口上需要加@Mapper注解
可以将@Mapper注解理解为@Component注解
4. 为每一个接口建立对应的映射文件
<?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="接口路径"> <cache/> <resultMap id="userResultMap" type="实体路径"> <id column="u_id" property="uId"/> <result column="email" property="email"/> <result column="password" property="password"/> <result column="login_count" property="loginCount"/> <result column="last_login_time" property="lastLoginTime" javaType="java.time.LocalDateTime" jdbcType="TIMESTAMP"/> </resultMap> <insert id="insert" parameterType="com.google.springmvc.domain.User" useGeneratedKeys="true" keyProperty="uId"> insert into users(email, password, login_count, last_login_time) values(#{email}, #{password}, #{loginCount}, #{lastLoginTime}) </insert> <update id="update" parameterType="com.google.springmvc.domain.User"> update users <trim prefix="set" suffixOverrides="," > <if test="email != null">email=#{email},</if> <if test="password != null">password=#{password},</if> <if test="loginCount != null">login_count=#{loginCount},</if> <if test="lastLoginTime != null">last_login_time=#{lastLoginTime}</if> </trim> where u_id=#{uId} </update> </mapper>
5. 在application.properties中进行SSM的基本配置
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf-8&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=用户名 spring.datasource.password=密码 mybatis.mapperLocations=classpath*:**/mappers/*.xml
6. 测试
@SpringBootTest class SpringmvcApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { System.out.println(userMapper.selectByEmailAndPassword("tom@google.com", "123456")); } }
(转换类型) @Component public class DateFormatter implements Formatter<LocalDate> { @Override public LocalDate parse(String s, Locale locale) throws ParseException { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return LocalDate.parse(s, dateTimeFormatter); } @Override public String print(LocalDate date, Locale locale) { return date.toString(); } }
7. 书写service层
7.1 在service层中使用@Autowired注入需要Mapper
7.2 在service层的每个实现类上加入@Service注解
7.3 在service层的每个实现类上加入@Transactional注解
8. 测试一下service层代码(也可以不测试)
9. 写controller层:在控制器层注入service层即可。例如:
@Controller public class StudentsController { @Autowired private StudentsService studentsService; @RequestMapping("/toSave") public String toSave() { return "saveStudent"; } @RequestMapping("/save") public String save(Students students){ studentsService.save(students); return "redirect:query"; }
10. 写网页或者json进行测试