spring boot mybatis配置
程序员文章站
2022-04-23 12:05:50
...
SpringBoot中添加mybatis数据库
- 添加model
public class UserInfo {
private String uid;
private String login_name;
private String username;
private String worker_id;
private String password;
private String position;
private String departments;
private String email;
private Integer status;
private boolean is_admin;
private String reserv2;
private int reserv1;
private String modifytime;
// getter and setter ...
}
- 添加Mapper
public interface UserMapper {
@Select("SELECT * FROM user_info WHERE uid = #{userId}")
UserInfo getUser(@Param("userId") String userId);
}
- 添加MapperScan
在Application配置中添加MapperScan
@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 在Service应用层引用
@Autowired
UserMapper userMapper;
@Override
public UserInfo getUserInfo() {
UserInfo userInfo = userMapper.getUser("1");
System.out.println("get UserInfo: " + userInfo);
return userInfo;
}
- 数据库配置
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/wt
username: wt
password: wt
- 数据库插入数据
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`uid` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`login_name` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`worker_id` varchar(16) COLLATE utf8_unicode_ci DEFAULT '',
`password` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`position` varchar(16) COLLATE utf8_unicode_ci DEFAULT '',
`departments` varchar(256) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT '',
`status` int(11) NOT NULL,
`is_admin` int(11) DEFAULT NULL,
`reserv2` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`reserv1` int(11) DEFAULT NULL,
`modifytime` datetime DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
create unique index idx_user_username on user_info(login_name);
INSERT INTO `user_info` VALUES ('1', 'login_name', '华通', '000', '1', '0', '', '[email protected]', 1, 1, '', 0, '2011-08-10 10:02:44');
在mybatis文档中,有datasource配置.但是使用 MyBatis-Spring 之后, 你不再需要直接使用SqlSessionFactory了,因为你的bean可以通过一个线程安全的SqlSession来注入,基于Spring的事务配置 来自动提交,回滚,关闭 session。
错误
stablishing SSL connection without server's identity verification
配置链接url时,需要在后面添加useSSL=false
url: jdbc:mysql://127.0.0.1:3306/wt?useSSL=false
疑问:
- 用yaml配置文件如何配置事务
推荐阅读
-
Spring Boot使用AOP防止重复提交的方法示例
-
spring boot 注入 property的三种方式(推荐)
-
Spring+MyBatis实现数据读写分离的实例代码
-
java 使用memcached以及spring 配置memcached完整实例代码
-
spring boot admin 搭建详解
-
Spring Boot集成Kafka的示例代码
-
SpringCloud之分布式配置中心Spring Cloud Config高可用配置实例代码
-
Spring Boot整合Spring Security的示例代码
-
在Spring Boot中使用swagger-bootstrap-ui的方法
-
Spring boot工具类静态属性注入及多环境配置详解