注解方式简单集成Mybatis
一、引入依赖,配置数据库连接
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
二、定义mapper和bean
@Mapper
public interface UserInfoMapper {
@Select("SELECT * FROM USER_INFO WHERE NAME = #{name}")
UserInfo findByName(String name);
}
@Data
public class UserInfo {
private int id;
private String money;
private String name;
}
测试:
@Autowired
private UserInfoMapper userInfoMapper;
@RequestMapping("/getuser")
public UserInfo getUser(){
return userInfoMapper.findByName("wc");
}
三、问题
1.注入mapper报错
对于此错误,是因为UserInfoMapper是接口,并没有实现类,在mapper上加注解:@Component(value = “userInfoMapper”) 即可。当然,这个错误只会影响观赏性,跟代码的运行没有关系,所以此注解非必须。
2.项目启动时报错:The server time zone value
对于错误:java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone,是因为mysql依赖包是高版本的情况下,在配置datasource.url不能简单配置为:
spring.datasource.url=jdbc:mysql://localhost:3306/chat
而应配置为
spring.datasource.url=jdbc:mysql://localhost:3306/chat?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
3. SSL connection must be established by default if explicit option isn't set
MySQL5.5.45之后的版本需要指定SSL参数:在mysql连接字符串url中加入ssl=true或者false即可,如下所示。
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
4.There is no PasswordEncoder mapped for the id "null"
Spring Security5.0新增了多种加密方式,也改变了密码的格式。密码的存储格式为:“{id}........”。前面的id是加密方式,id可以是bcrypt、sha256等,后面跟着的是加密后的密码。也就是说,程序拿到传过来的密码的时候,会首先查找被“{”和“}”包括起来的id,来确定后面的密码是被怎么样加密的,如果找不到就认为id是null。这也就是为什么我们的程序会报错:There is no PasswordEncoder mapped for the id “null”。
要想我们的项目还能够正常登陆,要将前端传过来的密码进行某种方式加密,spring security 官方推荐的是使用bcrypt加密方式。
//注入userDetailsService的实现类
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
5.@Autowired用于方法上
Spring会先实例化所有bean,然后再根据配置进行扫描,当检测到@Autowired后进行注入,注入时调用这个方法。@Autowired在方法上,实例化这个类的时候,注入方法形参类型的。
网友评论