美文网首页
MyBatis实现的三种方式

MyBatis实现的三种方式

作者: 煗NUAN | 来源:发表于2020-03-14 12:34 被阅读0次

    MyBatis实现的三种方式

    • 分类
      • 配置xx.xml文件式
      • 配置xx.xml文件+接口式
      • 纯注解式

    一.纯配置文件式

    • 是根据多表联合查询的例题

      • 需要根据查询的字段新建一个Javabean的类
    • 添加MyBatis的配置文件mybatis.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>
        <!--引入外部配置文件db.properties,连接数据库的时候直接引用db.properties中的key值就可以${driver}...-->
        <properties resource="db.properties" />
    
        <!--给当前mybatis项目添加日志功能,该STDOUT_LOGGING值的好处是不用添加第三方jar包就可以有日志输出-->
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
    
        <!--起别名使用package标签可以匹配com.yanm.pojo包下的所有类,并且不区分大小写
            也可使用typeAlias标签匹配指定类型-->
        <typeAliases>
            <package name="com.mybatis.dto" />
        </typeAliases>
    
        <!--配置mybatis环境变量-->
        <environments default="development">
            <environment id="development">
                <!--配置JDBC事务控制,由mybatis进行管理-->
                <transactionManager type="JDBC"/>
                <!--配置数据源,采用mybatis连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${user}"/>
                    <property name="password" value="${pass}"/>
                </dataSource>
            </environment>
        </environments>
        <!--加载映射文件-->
        <mappers>
            <!--使用资源的路径-->
            <mapper resource="mybatis1/OrderDTO.xml" />
        </mappers>
    </configuration>
    
    • 数据路连接的参数db.properties
    driver=org.mariadb.jdbc.Driver
    url=jdbc:mariadb://localhost:3306/mall
    user=root
    pass=root
    
    • 配置映射文件OrderDTO.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:配置名称空间,对配置的statement进行分类管理
            此时名称可以任意
            当使用Mapper代理时,namespace具有特殊的含义与功能
        -->
    <mapper namespace="mybatis1.OrderDTO">
    
        <select id="getOrderByUid" resultType="OrderDTO">
            select u.uname username,o.oprice orderprice, pa.paytype,d.dcount detailcount,p.pname productname,p.pimg productimgs,
            t.tname typename,i.iname imgname,a.address
            from users u
            inner join orders o on u.uid=o.uid
            inner join pays pa on pa.payid=o.payid
            inner join details d on o.oid=d.oid
            inner join products p on p.pid=d.pid
            inner join types t on t.tid=p.tid
            inner join imgs i on i.pid=p.pid
            inner join address a on a.aid=o.aid
            where u.uid = #{uid};
        </select>
    </mapper>
    
    • 根据查询的字段新建一个JavaBean的类(根据查询结果的名字,如果是有重命名,要用重命名)
    //使用lombok构造Javabean类
    @Data  //添加get和set方法
    @NoArgsConstructor   //空参构造
    @AllArgsConstructor  //全参构造
    public class OrderDTO {
        private String username;
        private String orderprice;
        private String paytype;
        private String detailcount;
        private String productname;
        private String productimgs;
        private String typename;
        private String imgname;
        private String address;
    }
    
    
    • 测试类DTOTest.java
    public class DTOTest {
        private SqlSessionFactory ssf=null;
        private SqlSession ss=null;
    
        @Before
        public void beforeSQL(){
            try {
                ssf=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
                ss=ssf.openSession(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @After
        public void afterSQL(){
            if (ss!=null){
                ss.close();
                ss=null;
            }
        }
    
        @Test
        public void testDTO(){
            List<OrderDTO> orderDTOs = ss.selectList("mybatis1.OrderDTO.getOrderByUid",1);
            for (OrderDTO orderDTO : orderDTOs) {
                System.out.println(orderDTO.toString());
            }
        }
    }
    

    二.配置xx.xml文件+接口式

    • 配置文件+接口实现MyBatis的要求
      1. namespace必须是接口的全路径
      2. 每个节点的id必须是接口中的方法名
      3. 该接口中的方法不允许重载,否则namespace+id将不唯一
      4. 注意该接口中的增删改的方法的返回值,最好使用int
    • 添加MyBatis的配置文件mybatis.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>
        <!--引入外部配置文件db.properties,连接数据库的时候直接引用db.properties中的key值就可以${driver}...-->
        <properties resource="db.properties" />
        
        <!--起别名使用package标签可以匹配com.yanm.pojo包下的所有类,并且不区分大小写
            也可使用typeAlias标签匹配指定类型-->
        <typeAliases>
            <package name="com.mybatis.pojo" />
        </typeAliases>
    
        <!--配置mybatis环境变量-->
        <environments default="development">
            <environment id="development">
                <!--配置JDBC事务控制,由mybatis进行管理-->
                <transactionManager type="JDBC"/>
                <!--配置数据源,采用mybatis连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${user}"/>
                    <property name="password" value="${pass}"/>
                </dataSource>
            </environment>
        </environments>
        <!--加载映射文件-->
        <mappers>
            <!--使用资源的路径-->
            <mapper resource="dao/IUserDao.xml" />
        </mappers>
    </configuration>
    
    • 数据路连接的参数db.properties
    driver=org.mariadb.jdbc.Driver
    url=jdbc:mariadb://localhost:3306/mall
    user=root
    pass=root
    
    • 配置映射文件IUserDao.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.mybatis.dao.IUserDao">
        <!--
        第二种实现mybatis的方式为:接口+xml方式
        这种方式有特别的要求
            1.  namespace必须是接口的全路径
            2.  每个节点的id必须是接口中的方法名
            3.  该接口中的方法不允许重载,否则namespace+id将不唯一
            4.  注意该接口中的增删改的方法的返回值,最好使用int
    -->
    
        <select id="getAllUsers" resultType="Users">
            select * from users
        </select>
    
        <select id="getUsersById" resultType="Users">
            select * from users where uid=#{uid}
        </select>
    
        <delete id="deleteUser">
            delete from users where uid=#{uid}
        </delete>
    
        <insert id="saveUser">
            insert into users values(DEFAULT,#{uname},#{upass},#{uphone},#{oid})
        </insert>
    
        <update id="updateUser">
            update users set uname=#{uname},upass=#{upass} where uid=#{uid}
        </update>
    
    </mapper>
    
    • Javabean类Users.java
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Users {
        private int uid;
        private String uname;
        private String upass;
        private String uphone;
        private int oid;
    }
    
    
    • 接口IUserDao.java
    public interface IUserDao {
    
        //获取用户信息
        List<Users> getAllUsers();
    
        //根据id获取用户信息
        Users getUsersById(int uid);
    
        //删除用户
        int deleteUser(int uid);
    
        //新增用户
        int saveUser(Users users);
    
        //修改用户信息
        int updateUser(Users users);
    }
    
    
    • 测试类MybatisTest.java
    public class MybatisTest {
    
        private SqlSession ss=null;
    
        @Before
        public void beforeSQL(){
            ss= SessionUtils.getSqlSession(); //调用工具类
        }
    
        @After
        public void afterSQL(){
            SessionUtils.SqlSessionClose(ss);  //调用工具类
        }
    
        @Test
        public void getAllUser(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            List<Users> list=dao.getAllUsers();
            for (Users users : list) {
                System.out.println(users);
            }
        }
    
        @Test
        public void getUsersById(){
            IUserDao dao=ss.getMapper(IUserDao.class);
    
            Users user = dao.getUsersById(1);
            System.out.println(user);
        }
    
        @Test
        public void deleteUser(){
            IUserDao dao=ss.getMapper(IUserDao.class);
    
            int i = dao.deleteUser(11);
            System.out.println(i);
        }
    
        @Test
        public void saveUser(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            Users users=new Users(0,"nihoa","nihao","12345678901",1);
            int i = dao.saveUser(users);
            System.out.println(i);
        }
    
        @Test
        public void updateUser(){
            IUserDao dao=ss.getMapper(IUserDao.class);
    
            Users users=new Users();
            users.setUid(4);
            users.setUname("甄宓");
            users.setUpass("zhenfu");
            int i = dao.updateUser(users);
            System.out.println(i);
        }
    }
    
    
    • SqlSession的工具类
    public class SessionUtils {
        private static SqlSessionFactory ssf=null;
        private static SqlSession ss=null;
    
        static {
            try {
                ssf=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //获取SqlSession对象
        public static SqlSession getSqlSession(){
            ss=ssf.openSession(true);
            return ss;
        }
    
        //关闭SqlSession对象
        public static void SqlSessionClose(SqlSession s){
            if (s!=null){
                s.close();
                s=null;
            }
        }
    }
    
    

    三.纯注解式

    • 添加MyBatis的配置文件mybatis.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>
        <!--引入外部配置文件db.properties-->
        <properties resource="db.properties" />
    
        <!--起别名使用package标签可以匹配com.mybatis.pojo包下的所有类,并且不区分大小写
            也可使用typeAlias标签匹配指定类型-->
        <typeAliases>
            <package name="com.mybatis.pojo" />
        </typeAliases>
    
        <!--配置mybatis环境变量-->
        <environments default="development">
            <environment id="development">
                <!--配置JDBC事务控制,由mybatis进行管理-->
                <transactionManager type="JDBC"/>
                <!--配置数据源,采用mybatis连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${user}"/>
                    <property name="password" value="${pass}"/>
                </dataSource>
            </environment>
        </environments>
        <!--加载映射文件-->
        <mappers>
            <!--使用资源的路径,匹配com.mybatis.dao包下的所有接口-->
            <package name="com.mybatis.dao"/>
        </mappers>
    </configuration>
    
    
    • 数据路连接的参数db.properties
    driver=org.mariadb.jdbc.Driver
    url=jdbc:mariadb://localhost:3306/mall
    user=root
    pass=root
    
    
    • 接口
    public interface IUserDao {
    
        //获取用户信息
        @Select("select * from users")
        List<Users> getAllUsers();
    
        //查询指定字段
        @Select("select * from users where uname=#{param1} and upass=#{param2}")
        //或者 : 
        // @Select("select * from users where uname=#{arg0} and upass=#{arg2}")
        Users getUserAndPassword(String uname,String upass);
    
        /**
         *   或者 :
         *      @Select("select * from users where uname=#{uname} and upass=#{upass}")
         *      Users getUserAndPassword(@Param("uname")String uname,@Param("upass")String upass);
        */
    
    
        //查询用户
        @Select("select * from users where uid=#{aaa}")
        Users getUserById(int uid);
    
        //添加用户
        @Insert("insert into users values(default,#{uname},#{upass},#{uphone},#{oid})")
        int saveUser(Users users);
    
        //删除用户
        @Delete ("delete from users where uid=#{uid}")
        int deleteUserById(int uid);
    
    
        //根据id修改信息
        @Update("update users set uname=#{uname},upass=#{upass} where uid=#{uid}")
        int updateUserById(Users users);
    }
    
    
    • Javabean类
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Users {
        private int uid;
        private String uname;
        private String upass;
        private String uphone;
        private int oid;
    }
    
    
    • 测试类MybatisTest.java
    public class MybatisTest {
    
        private SqlSession ss=null;
        @Before
        public void beforeSQL(){
            ss= SessionUtils.getSqlSession();
        }
        @After
        public void afterSQL(){
            SessionUtils.SqlSessionClose(ss);
        }
    
        @Test
        public void getAllUsers(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            List<Users> list=dao.getAllUsers();
            for (Users users : list) {
                System.out.println(users);
            }
        }
    
        @Test
        public void loginTest(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            Users users=dao.getUserAndPassword("大乔","daqiao");
            System.out.println(users);
        }
    
    
        @Test
        public void getUserById(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            Users users=dao.getUserById(2);
            System.out.println(users);
        }
    
        @Test
        public void saveUser(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            int i=dao.saveUser(new Users(0,"你好","nihao","1234",1));
            System.out.println(i);
        }
    
        @Test
        public void deleteUserById(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            int i = dao.deleteUserById(4);
            System.out.println(i);
        }
    
        @Test
        public void updateUserById(){
            IUserDao dao=ss.getMapper(IUserDao.class);
            Users users=new Users();
            users.setUid(12);
            users.setUname("甄宓");
            users.setUpass("zhenfu");
            int i = dao.updateUserById(users);
            System.out.println(i);
        }
    }
    
    
    • 创建和关闭SqlSession的工具类SessionUtils.java
    public class SessionUtils {
        private static SqlSessionFactory ssf=null;
        private static SqlSession ss=null;
    
        static {
            try {
                ssf=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //获取SqlSession对象
        public static SqlSession getSqlSession(){
            ss=ssf.openSession(true);
            return ss;
        }
    
        //关闭SqlSession对象
        public static void SqlSessionClose(SqlSession s){
            if (s!=null){
                s.close();
                s=null;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:MyBatis实现的三种方式

          本文链接:https://www.haomeiwen.com/subject/lypvshtx.html