1. 在 mapper 创建对应的 sql 语句
<!--namespace 自己命名 -->
<mapper namespace="Usermappar">
<!--查询-->
<select id="selectUserById" parameterType="Integer" resultType="bean.User">
select * from user where id = #{id}
</select>
<!--//新增-->
<insert id="insertUser" parameterType="bean.User">
insert into user value (#{id},#{name},#{age})
</insert>
<!--修改-->
<update id="updatetUser" parameterType="bean.User">
update user set name = #{name} where id = #{id}
</update>
<!--删除-->
<delete id="delelctUserById" parameterType="Integer">
delete from user where id = #{id}
</delete>
</mapper>
2. 进行操作
公共代码
//读取配置文件
String resource = "sqlMapConfig.xml";
InputStream in= Resources.getResourceAsStream(resource);
//需要sqlSessionfactoryBulider
SqlSessionFactoryBuilder builder= new SqlSessionFactoryBuilder();
//创建需要sqlSessionfactory
SqlSessionFactory sessionFactory= builder.build(in);
//生产一个sqlSession
SqlSession sqlSession=sessionFactory.openSession();
User user =new User();
user.setId(6);
user.setName("baba");
//新增
sqlSession.insert("Usermappar.insertUser",user);
sqlSession.commit();
//删除
sqlSession.delete("Usermappar.delelctUserById",6);
sqlSession.commit();
User user =new User();
user.setId(6);
user.setName("lala");
//修改
sqlSession.update("Usermappar.updatetUser",user);
sqlSession.commit();
//查询
User user = sqlSession.selectOne("Usermappar.selectUserById",0);
网友评论