一、流程模板
//1. 配置mybatis
Configuration configuration = configuration();
//2. 获取SqlSessionFactory
SqlSessionFactory sessionFactory = new DefaultSqlSessionFactory(configuration);
//3. 获取Session
SqlSession sqlSession = sessionFactory.openSession(true);
//4. 获取Mapper
OrignUserMapper mapper = sqlSession.getMapper(OrignUserMapper.class);
三、代码实战
1. 建表结构
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
2. Bean
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
3. Mapper代码
Mapper �接口绑定实现方式(三种)? 本例使用第二种。
- 1.通过 XML Mapper 里面写 SQL 来绑定。
- 2.通过注解绑定,就是在接口的方法上面加上 @Select、@Update、@Insert、@Delete 注解。
- 3.通过注解绑定,在接口的方法上面加上 @SelectProvider、@UpdateProvider、@InsertProvider、@DeleteProvider 注解,通过 Java 代码,生成对应的动态 SQL
public interface OrignUserMapper {
@Select(" select name from user where id = #{l} ")
User selectById(long l);
@Insert(" insert into `user_center`.`user` ( `id`, `age`, `email`, `name`) values (#{id}, #{age}, #{email}, #{name}); ")
long insert(User user);
}
4. 测试类
/**
* @ClassName : MybatisTest
* @Description : 手动获取mapper测试
* @Author : hack2012
* @Date: 2020-12-18 04:24
*/
public class MybatisTest {
@Test
public void testConnect(){
//1. 配置mybatis
Configuration configuration = configuration();
//2. 获取SqlSessionFactory
SqlSessionFactory sessionFactory = new DefaultSqlSessionFactory(configuration);
//3. 获取Session
SqlSession sqlSession = sessionFactory.openSession(true);
//4. 获取Mapper
OrignUserMapper mapper = sqlSession.getMapper(OrignUserMapper.class);
long id = 2l;
User user = new User();
user.setId(id);
user.setName("name1");
user.setAge(20);
user.setEmail("aaaa@aa.com");
long insert = mapper.insert(user);
System.out.println(insert);
User user_new = mapper.selectById(id);
System.out.println(user_new);
}
private Configuration configuration(){
Configuration configuration = new Configuration();//new MybatisConfiguration();
//1. 设置环境配置
configuration.setEnvironment(getEnv());
//2. 添加mapper映射
configuration.addMapper(OrignUserMapper.class);
//设置下划线转驼峰命名
// configuration.setMapUnderscoreToCamelCase(true);
return configuration;
}
//初始化环境配置
public Environment getEnv(){
TransactionFactory transFactory = new JdbcTransactionFactory();
MysqlDataSource datasource = new MysqlDataSource();
datasource.setUrl("jdbc:mysql://xxxxxxxx:13306/user_center?&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false");
datasource.setUser("root");
datasource.setPassword("xxxxxxxxxxxxxxx");
return new Environment("did", transFactory, datasource);
}
}