DBUtils 要设置为单例模式
public enum DBUtil {
INSTANCE;
private SqlSessionFactory sessionFactory;
private DBUtil() {
String resource = "mybatis-config.xml";
try (Reader reader = Resources.getResourceAsReader(resource)){
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
}
1 有关配置(mybatis-config.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">
<configuration>
<!-- 这个要注意是要放在typeAliases标签的前面 不然会报错-->
<settings>
<!-- 开启数据库下划线命名方式和 java 驼峰命名方式之间的转换 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<!-- 设置别名,使用别名代替原始的名字 -->
<typeAlias type="com.rjxy.model.User" alias="_User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/数据库名" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 使用 xml 的方式配置 --> <!-- 这个是常用的方法 -->
<mapper resource="UserMapper.xml" /> <!--这个对应另一个类的Mapper-->
<!-- 使用注解的方式配置 -->
<mapper class="com.rjxy.dao.CategoryDao"/>
</mappers>
</configuration>
2 有关UserMapper.xml
<?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="com.rjxy.dao.UserDao">
<insert id="saveUser" parameterType="_User">
insert into user(username, password, email) values (#{username}, #{password}, #{email})
</insert>
<select id="listUser" resultType="_User">
select * from user
</select>
</mapper>
3 注解的方式配置 , 不需要 CategoryMapper.xml (但是不常用 , 不方便) 对应上面相同颜色
4 模糊查询 , 如果有多个传参数模糊查询
总共有三种方法:
1. 封装为对象
2. 使用 HashMap
3. 使用参数索引:
arg0,arg1,...
param1,param2,...
select * from user where username like #{value}
listUserByKey("%人%");
<select id="listUserByName" parameterType="String" resultType="_User">
select * from user where username like '%${value}%'
</select>
dao.listUserByKey("人");
<select id="listUserByNameOrEmail" resultType="_User">
select * from user where username like #{param1} or email like #{param2}
</select>
<select id="listUserByNameOrEmail" resultType="_User">
select * from user where username like #{arg0} or email like #{arg1}
</select>
dao.listUserByNameOrEmail("%a%", "%q%");