标签:
增加
@Test public void addTest(){ String resource = "mybatis-config.xml"; SqlSession sqlSession = null; try { User user = new User(); user.setUserCode("aaaa"); user.setUserName("xxxx"); InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); sqlSession = factory.openSession(); sqlSession.insert("cn.bdqn.dao.UserMapper.add",user); sqlSession.commit(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); sqlSession.rollback(); }finally{ 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+id(方法名)的名字就可以访问 --> <mapper namespace="cn.bdqn.dao.UserMapper"> <!-- id要唯一的,一般是下拉类的方法名 --> <!-- 返回的是什么类型int --> <select id="count" resultType="int"> select count(1) from user </select> <!-- 增加 --> <insert id="add" parameterType="User"> insert into user(userCode,userName,userPassword) values (#{userCode},#{userName},#{userPassword}) </insert> <!-- 修改 --> <update id="update" parameterType="User"> update user set userCode=#{userCode},userName=#{userName}, userPassword=#{userPassword} where id=#{id} </update> <!-- 删除 --> <delete id="delete" parameterType="User"> delete from user where id=#{id} </delete> </mapper>
在UserMapper.xml中的parameterType="cn.bdqn.pojo.User" 添加别名为User这样就方便些
<!-- 引入 jdbc.properties 文件--> <properties resource="jdbc.properties"/> <!-- alias别名 --> <typeAliases> <typeAlias type="cn.bdqn.pojo.User" alias="User"/> </typeAliases>
标签:
原文地址:http://www.cnblogs.com/xuerong/p/4958012.html