<!-- 占位符#{} 类似于JBDC的占位符,比如上面的sql语句,传入Integer10时,它就是把Integer10填在占位符的位置如果是String10,就是把String10填在里面。里面的参数可以随便填,但不能为空。${} 字符串拼接,如下面的sql语句,传入"五",最终注入数据库的是"%五%"。里面的参数只能写value#{} 占位符实现字符串拼接,"%${value}%" <==> "%"#{v}"%"--><selectid="findUsersByName"parameterType="String"resultType="com.pojo.User">select * from user where username like "%${value}%"
</select>
publicvoidinsert() throws Exception {//1、加载核心配置文件String coreXml = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(coreXml);//2、创建工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//3、获得sqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();//4、执行sql语句User user = new User("helloworld", "2", new Date(), "aaaaaa");int i = sqlSession.insert("User.insert", user);//默认是不自动提交事务sqlSession.commit();//5、处理结果System.out.println(i);
}
publicvoidinsert() throws Exception {//1、加载核心配置文件String coreXml = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(coreXml);//2、创建工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//3、获得sqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();//4、执行sql语句User user = new User("helloworld", "2", new Date(), "aaaaaa");int i = sqlSession.insert("User.insert", user);//默认是不自动提交事务sqlSession.commit();//5、处理结果System.out.println(user.getId());
}
更新用户
<update id="updateUser" parameterType="com.pojo.User">update user set username = #{
username}, sex = #{
sex}, birthday = #{
birthday}, address = #{
address}where id = #{
id}
</update>
@org.junit.Test
publicvoidupdate() throws Exception {//1、加载核心配置文件String coreXml = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(coreXml);//2、创建工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//3、获得sqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();//4、执行sql语句User user = new User("helloworld", "1", new Date(), "aaaaaa");user.setId(1);int i = sqlSession.update("User.updateUser", user);//默认是不自动提交事务sqlSession.commit();//5、处理结果
}
删除
<update id="delete" parameterType="Integer">delete from user whereid = #{aaa}
</update>
@org.junit.Test
publicvoiddelete() throws Exception {//1、加载核心配置文件String coreXml = "sqlMapConfig.xml";InputStream in = Resources.getResourceAsStream(coreXml);//2、创建工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//3、获得sqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();//4、执行sql语句User user = new User("helloworld", "1", new Date(), "aaaaaa");user.setId(1);int i = sqlSession.delete("User.delete", 28);//默认是不自动提交事务sqlSession.commit();//5、处理结果
}