学习了Mybatis。相对于hibernate来说这个框架更加灵活,开发效率更快,适用于那些改动比较频繁的项目。
首先加入mybatis的配置文件myBatisConfig.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>
<settings>
<!-- 懒加载开启 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 为真,直接查询关联数据,为假按需查询 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 配置数据库连接信息 -->
<properties resource="db.properties"/>
<!-- 别名定义 ,一定要放在environments标签前面-->
<typeAliases>
<!-- 单个类别名定义 -->
<!-- <typeAlias type="com.samrtian.entity.User" alias="User"/> -->
<!-- 批量,扫描整个包别名定义,名字就是类名 -->
<package name="com.samrtian.entity"/>
</typeAliases>
<!-- 连接信息 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.connect}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射文件 -->
<mapper resource="sqlMap/User.xml"/>
<!-- 代理方法映射文件 -->
<!-- <mapper resource="com/samrtian/mapper/UserMapper.xml"/> -->
<!-- 通过代理接口映射文件XML和类名必须一致且在同一个目录内 -->
<!-- <mapper class="com.samrtian.mapper.UserMapper"/> -->
<!-- 通过包名批量加载代理接口映射文件 -->
<package name="com.samrtian.mapper"/>
</mappers>
</configuration>
下边是db.properties的数据库配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.connect=jdbc:mysql://localhost:3306/bls?serverTimezone=GMT
jdbc.username=root
jdbc.password=ytfmnm
然后是加入映射文件我们下边用的事mapper的代理方法,这样方便快捷
<?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">
<!-- 这里的namespace是对应的代理类名 -->
<mapper namespace="com.samrtian.mapper.UserMapper">
<!-- 让这个mapper启用二级缓存, 并且把相关的实体类实现序列化 -->
<!-- <cache type="使用哪些二级缓存类"/> -->
<select id="findByUserID" parameterType="java.lang.Integer" resultType="com.samrtian.entity.User">
select * from t_user where id = #{id}
</select>
<select id="findByUserName" parameterType="java.lang.String" resultType="com.samrtian.entity.User">
select * from t_user where name = #{value}
</select>
<select id="findLikeUserName" parameterType="java.lang.String" resultType="com.samrtian.entity.User">
select * from t_user where name like '%${value}%'
</select>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from t_user where id = #{id}
</delete>
<update id="updateUser" parameterType="User">
update t_user set name = #{name}, password = #{password} where id = #{id}
</update>
<insert id="insertUser" parameterType="com.samrtian.entity.User">
<!-- 插入数据后ID自动填充到User里边,因为是先提交插入到数据库里边才生成的ID所以用AFTER -->
<selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
INSERT into t_user(name, password) VALUES(#{name}, #{password});
</insert>
<!-- 定义一个SQL片段 -->
<sql id="sql_user_where">
<if test="user!=null">
<if test="user.name!=null">
and name = #{user.name}
</if>
<if test="user.password">
and password = #{user.password}
</if>
</if>
</sql>
<!-- 多参数的话自定义一个包装类VO,把条件当属性添加进去 , user是CustomVo里边的一个属性-->
<!-- 只有当属性成员user和里边的属性值不为空的话才会拼接条件 -->
<select id="findByUserInfo" parameterType="com.samrtian.po.CustomVo" resultType="User">
select * from t_user
<where>
<!-- 如果这段查询条件经常用到的话可以定义一个SQL片段,这样的话可以复用 -->
<!-- <if test="user!=null"> -->
<!-- <if test="user.name!=null"> -->
<!-- and name = #{user.name} -->
<!-- </if> -->
<!-- <if test="user.password"> -->
<!-- and password = #{user.password} -->
<!-- </if> -->
<!-- </if> -->
<include refid="sql_user_where"/>
</where>
</select>
<!-- 当查出来的结果集列名与POJO的属性名不一致时可以做一个映射这样就可以查询出来结果集了 -->
<resultMap type="User" id="UserMap">
<id column="id_" property="id"/>
<result column="n_" property="name"/>
<result column="p_" property="password"/>
</resultMap>
<select id="findByidResultMap" parameterType="int" resultMap="UserMap">
select id id_, name n_, password p_ from t_user where id = #{id}
</select>
<!-- 以列表为参数 -->
<select id="findByIds" parameterType="list" resultType="User">
select * from t_user
<where>
<if test="list!=null">
<foreach collection="list" item="user_id" open="and id in (" close=")" separator=",">
#{user_id}
</foreach>
</if>
</where>
</select>
<!-- association标签是用来标识一对一的关系映射也可以实现懒加载 -->
<resultMap type="com.samrtian.po.CustomVo" id="Cv">
<result column="GroupName" property="groupName"/>
<association property="user" javaType="User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
<result column="groupid" property="groupID"/>
</association>
</resultMap>
<select id="findByidAss" parameterType="int" resultMap="Cv">
SELECT u.*, g.GroupName FROM t_user u, t_groupwork g
WHERE u.groupid = g.GroupID AND u.id = #{id}
</select>
<!-- collection标签是用来标识一对多关系映射 select是延迟加载-->
<!-- <resultMap type="" id="" extends=""> -->
<!-- <collection property="属性名" ofType="多的那个类型" select="上边的select ID"> -->
<!-- <id/> -->
<!-- <result/> -->
<!-- </collection> -->
<!-- </resultMap> -->
<!-- <select id=""> -->
<!-- </select> -->
<!-- collection标签也可以用来标识多对多关系映射 -->
<!-- <resultMap type="" id="" extends=""> -->
<!-- <collection property="属性名" ofType="多的那个类型"> -->
<!-- <id/> -->
<!-- <result/> -->
<!-- <collection property=""> -->
<!-- </collection> -->
<!-- </collection> -->
<!-- </resultMap> -->
<!-- <select id=""> -->
<!-- </select> -->
</mapper>
下边是映射文件对应的代理接口类
package com.samrtian.mapper;
import java.util.List;
import com.samrtian.entity.User;
import com.samrtian.po.CustomVo;
public interface UserMapper {
public User findByUserID(int id);
public User findByUserName(String name);
public List<User> findLikeUserName(String name);
public void insertUser(User user);
public void deleteUser(int id);
public void updateUser(User user);
public User findByUserInfo(CustomVo vo);
public User findByidResultMap(int id);
public List<User> findByIds(List<Integer> list);
public CustomVo findByidAss(int id);
}
代理接口类的方法与xml映射文件的id要一致包括参数和返回类型.
下边来测试使用方法
package test_ssh;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.samrtian.entity.User;
import com.samrtian.mapper.UserMapper;
import com.samrtian.po.CustomVo;
public class test {
@Test
public void select() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
User user = session.selectOne("nsUser.findByUserID", 1);
System.out.println(user.getName() + " " + user.getPassword());
session.close();
}
@Test
public void like() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
List<User> list = session.selectList("nsUser.findLikeUserName", "xu");
System.out.println(list);
session.close();
}
@Test
public void insert() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
User user = new User();
user.setName("xiaohu");
user.setPassword("fsdfds");
session.insert("nsUser.insertUser", user);
session.commit();
System.out.println(user);
session.close();
}
@Test
public void delete() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
session.delete("nsUser.deleteUser", 334);
session.commit();
session.close();
}
@Test
public void update() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
User user = new User();
user.setId(888);
user.setName("kongjinxiang");
user.setPassword("55555");
session.update("nsUser.updateUser", user);
session.commit();
session.close();
}
@Test
public void testMapper() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.findByUserID(888);
session.close();
System.out.println(user);
}
@Test
public void testMultiParam() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
CustomVo vo = new CustomVo();
User user = new User();
user.setName("xiaohu");
user.setPassword("fsdfds");
vo.setUser(user);
userMapper.findByUserInfo(vo);
session.close();
System.out.println(user);
}
@Test
public void testResultMap() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.findByidResultMap(1);
session.close();
System.out.println(user);
}
@Test
public void testUsersForID() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(5);
List<User> users = userMapper.findByIds(list);
session.close();
System.out.println(users);
}
@Test
public void testAssociation() throws IOException {
String resource = "myBatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
CustomVo user = userMapper.findByidAss(1);
session.close();
System.out.println(user.getUser().toString() + " " + user.getGroupName());
}
}
测试成功。都没问题