导包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
配置指定数据实体的映射文件,用于代码调用(解除SQL语句的耦合)
UserMapper.xml 指定实体为User类
这里namespace+id的SQL语句定位会在代码中使用从而调用相应SQL语句,
注意resultType中,属性要与数据库表的字段一致
<?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="userMapper">
<select id="findAll" resultType="com.CakeCN.domain.User">
select * from user
</select>
</mapper>
Mybatis核心配置文件 引用数据实体的映射文件
sqlMapConfig.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>
<!-- 数据源环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
<property name="username" value="root"/>
<property name="password" value="12138ckC"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
调用
@Test
public void test2() throws IOException {
//获取核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = factory.openSession();
List<User> list = sqlSession.selectList("userMapper.findAll");
System.out.println(list);
sqlSession.close();
}
插入语句
映射的写法 #{}
中是数据实体的属性名,对应到插入的各个字段
<insert id="save" parameterType="com.CakeCN.domain.User">
insert into user values (#{id}, #{username}, #{password})
</insert>
调用的写法
sqlSession.insert("userMapper.save",new User("CakeCN","pswdpswd"));
sqlSession.commit();
修改语句
<update id="update" parameterType="com.CakeCN.domain.User">
update user set username = #{username}, password = #{password} where id = #{id}
</update>
sqlSession.update("userMapper.update", new User(1,"CakeCN@OPL","pswd1pswd2"));
sqlSession.commit();
删除语句
其中传递的参数只需要是一个int,因此#{}
中填什么名字都可以
<delete id="deleteSpecificUser" parameterType="java.lang.Integer">
delete user where id=#{id}
</delete>
sqlSession.delete("userMapper.deleteSpecificUser",1);
sqlSession.commit();