Mybatis学习笔记1
mybatis是一个orm持久化框架,mybatis专注于sql的操作
从3.0开始名字改变了:ibatis-mybatis
对象关系映射(Object Relational Mapping)
一、Mybatis搭建
1、导包
2、mybatis-config.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/crm"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers><!-- 映射文件 现在不要配 ,有映射文件需要配在这里 包名前面的不要--> <mapper resource="com/zy/mapper/UserMapper.xml"/> </mappers> </configuration>
3、创建表
4、创建实体类
package com.zy.entity; public class User { private Integer uid; private String username; private String password; private String address; public User() { super(); // TODO Auto-generated constructor stub } public User(Integer uid, String username, String password, String address) { super(); this.uid = uid; this.username = username; this.password = password; this.address = address; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", address=" + address + "]"; } }
5、搭建映射文件
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"> <!-- namespace唯一表示此名字下的crud语句 --> <mapper namespace="myuser"><!-- 无规律,起个代号就行,不要重复 --> <!-- 提供了增删改查的相关标签 --> <!-- 以后的sql都会写在这个配置文件中 --> <!--<select id=""></select> <insert id=""></insert> <delete id=""></delete> <update id=""></update> --> <!-- 查询 --> <!-- 如果结果是集合也填集合的泛型 --> <!-- id:在此命名空间下唯一标识 resultType:查询结果的返回类型或者集合的泛型 --> <select id="selectUser" resultType="com.zy.entity.User"> SELECT * FROM t_user </select> <delete id="deleteUser"> DELETE FROM t_user WHERE uid=1 </delete> <insert id="insertUseer"> INSERT INTO t_user VALUES(NULL,'bbbb','1234','德国') </insert> <update id="updateUser"> UPDATE t_user SET username='武磊' WHERE uid=4 </update> <!-- 根据id查询用户 --> <select id="selectUserByid" resultType="com.zy.entity.User"> SELECT * FROM t_user WHERE uid=#{id}<!-- 一个参数#{}占位符,里面写什么无所谓 --> </select> <!-- 根据用户名和密码查询用户 --> <select id="selectUserByNP" resultType="com.zy.entity.User"> SELECT * FROM t_user WHERE username=#{uu} AND password=#{pp} </select> <!-- 特殊字符的转义 <![CDATA[]]> --> <!-- xml把小于号当做标签 在sql语句中直接写小于号会报错 --> <!-- The content of elements must consist of well-formed character data or markup. --> <select id="selectUser007" resultType="com.zy.entity.User"> <![CDATA[ SELECT * FROM t_user WHERE uid<9 ]]> </select> <!-- 多条件查询之对象传值 占位符要与对象属性保持一致,不然传不上去 --> <insert id="insertUser007"> INSERT INTO t_user VALUES(NULL,#{username},#{password},#{address}) </insert> </mapper>
<!-- 该实体类与表中列名有不一致的 使用as命别名解决 --> <select id="uu" resultType="com.zy.entity.UU"> SELECT uid id,username name,password,address from t_user </select>
6、在配置文件中引用映射文件
<mapper resource="com/zy/mapper/UserMapper.xml"/>
7、得到会话
package com.zy.test; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.zy.entity.User; public class UserTest { public static void main(String[] args) throws Exception { //1读取配置文件得到会话工厂 InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml"); //2sql会话工厂创建者 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //3生成sql会话工厂 SqlSessionFactory sf = sqlSessionFactoryBuilder.build(resourceAsStream); //4得到mybatis和数据库会话对象 SqlSession session = sf.openSession(); //完成一个查询任务 /*// List<User> selectList = session.selectList("myuser.selectUser"); // for (User user : selectList) { // System.out.println(user); // } //完成一个删除任务(增删改需要提交事务commit) // int delete = session.delete("myuser.deleteUser"); // session.commit();//相当于应用改变 //完成一个添加 // session.insert("myuser.insertUseer"); // session.commit(); //完成一个修改 // session.update("myuser.updateUser"); // session.commit(); //带一个参数的查询 // User uu = session.selectOne("myuser.selectUserByid",2); // System.out.println(uu); //带两个参数的查询 //解决方案1把参数放对象中 2把参数放map中[map中的键需要与占位符一致] 灵活度更高 // Map<Object, Object> map = new HashMap(); // map.put("uu", "rose"); // map.put("pp", "654321"); // // User uu = session.selectOne("myuser.selectUserByNP", map); // System.out.println(uu); //调用带<号的 // List<User> selectList = session.selectList("myuser.selectUser007"); // for (User uu : selectList) { // System.out.println(uu); // } */ //用对象传递参数 session.insert("myuser.insertUser007",new User(null, "哈哈", "111111", "郑州")); session.commit(); } }
8、使用mapper代理的方式
1).在实现的时候,查询字符串,需要namespace.sqlid,容易拼接出错,硬编码
2).参数是object类型,如果参数传入有问题,在编译的时候不报错
3).selectOne和seletList还需要判断
上述写法,有很多吐槽点,所以需要改成主流的方法
使用mapper代理的方式
package com.zy.mapper; import java.util.List; import com.zy.entity.User; public interface UserMapper { //UserMapper.java接口和UserMapper.xml配套使用----关系密切 //查询用户 public List<User> getList(); //根据id删除用户 public void deleteById(int id); }
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.zy.mapper.UserMapper"> <!-- 查询用户 1 namespace必须是接口全名称 2 id名必须和方法名一致 3 resultType和方法名的返回值保持一致,如果是集合和集合的泛型保持一致 4 接口和xml名字一致,放在同一包下 --> <select id="getList" resultType="com.zy.entity.User"> SELECT * FROM t_user </select> <delete id="deleteById"> DELETE FROM t_user WHERE uid=#{id} </delete> </mapper>
package com.zy.test; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.zy.entity.User; import com.zy.mapper.UserMapper; public class Test { public static void main(String[] args) throws Exception { //新形势下,使用mapper代理完成调用 //1读取配置文件得到会话工厂 InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml"); //2sql会话工厂创建者 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //3生成sql会话工厂 SqlSessionFactory sf = sqlSessionFactoryBuilder.build(resourceAsStream); //4得到mybatis和数据库会话对象 SqlSession session = sf.openSession(); //--------------------------- //旧的 //完成一个查询任务 // List<User> selectList = session.selectList("myuser.selectUser"); // for (User user : selectList) { // System.out.println(user); // } //------------------------------------ //新的 //得到一个mapper代理 // UserMapper mapper = session.getMapper(UserMapper.class);//反射 UserMapper为接口 // //代理调用方法去查询 // List<User> list = mapper.getList(); // //遍历 // for (User user : list) { // System.out.println(user); // // } //------------------------ UserMapper mapper = session.getMapper(UserMapper.class); mapper.deleteById(4); session.commit(); } }