Mybatis执行sqlSession.insert()和sqlSession.update()
在执行sqlSession.insert()和sqlSession.update()后需要进行 sqlSession.commit(),否则数据库不会插入数据,而且自增长id的情况下,在下一次成功的时候,会将未commit的数据id跳过。
@Test
public void testUpdate(){
//mybatis配置文件
String resource = "conf.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = MyTest1.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql的sqlSession
SqlSession sqlSession = factory.openSession();
String statement1 = "com.test.my.mapping.userMapper.updateUser";
User user1 = new User();
user1.setId(1);
user1.setName("马超");
user1.setAge(60);
int update = sqlSession.update(statement1, user1);
//如果没有commit,数据库是不会插入数据的
sqlSession.commit();
sqlSession.close();
}
@Test
public void testAdd(){
//mybatis配置文件
String resource = "conf.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = MyTest1.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql的sqlSession
SqlSession sqlSession = factory.openSession();
String statement1 = "com.test.my.mapping.userMapper.insertOne";
User user1 = new User();
user1.setId(1);
user1.setName("马超");
user1.setAge(60);
sqlSession.insert(statement1, user1);
sqlSession.commit();
sqlSession.close();
}
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.test.my.mapping.userMapper">
<sql id="Base_Column_List">
id,name,age
</sql>
<!--根据id获取-->
<select id="getUserById" parameterType="int" resultType="com.test.my.domain.User">
SELECT
<include refid="Base_Column_List"/>
FROM users WHERE id=#{id}
</select>
<!--新增-->
<insert id="insertOne" parameterType="com.test.my.domain.User">
insert into users(`name`,age) values (#{name},#{age})
</insert>
<!--删除-->
<delete id="deleteOne" parameterType="com.test.my.domain.User">
delete from users where id=#{id}
</delete>
<!--更新-->
<update id="updateUser" parameterType="com.test.my.domain.User">
update users set name = #{name},age = #{age} where id=#{id}
</update>
<!--查询所有-->
<select id="selectAll" parameterType="com.test.my.domain.User">
select <include refid="Base_Column_List"/> from users
</select>
</mapper>
conf.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"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="userMapper.xml"/>
</mappers>
</configuration>
记录学习