mybatis配置
mysql.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3326/sqlname?useUnicode=true&characterEncoding=utf-8
username=root
password=root
mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--没有集成spring时可以用,集成spring后这个文件主要内容都做spring配置文件中完成-->
<configuration>
<!--指定链接数据库信息位置-->
<properties resource="mybatis/mysql.properties"/>
<!--设置类别名,默认引入该包下的所有类,这样写mapper文件的时候可以只写entitiy的类名,而不用写全名;-->
<typeAliases>
<package name="com.jay.entities" />
</typeAliases>
<!--配置mysql的链接信息,数据从配置文件里读取-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="com/jay/dao/UserStateMapper.xml" />
</mappers>
</configuration>
数据库操作测试
@Test
public void insert() {
// mybatis链接sql配置
InputStream stream = UserStateServiceImplTest.class.getClassLoader().getResourceAsStream("mybatis/mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
SqlSession session = factory.openSession(true);
try {
// 扫描映射层文件
UserStateMapper userStateMapper = session.getMapper(UserStateMapper.class);
// 组装数据
UserState userState = new UserState();
userState.setId(0L);
userState.setUserId(0L);
userState.setType(0);
userState.setLastTime(new Date());
// 测试数据库添加数据
int insert = userStateMapper.insert(userState);
System.out.println("insert=" + insert);
// List<UserState> userStates = userStateMapper.find();
// userStates.forEach(userState1 -> System.out.println(userState1.toString()));
} finally {
session.close();
}
System.out.println("插入完成!");
}
运行: