05 mybatis的dao实现

传统实现方式与代理实现方式不同处在于代理实现方式省略了接口的实现类

传统实现方式
添加MyBatis的坐标

pom.xml

主要是mysql及mybatis坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>chen.li.com</groupId>
    <artifactId>itheima_mybatis_quick</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>


</project>
编写User实体类
package li.chen.com.business.entity;
public class User {      
    private Integer id;      
    private String userName;  
    private String passWord;      
    private String phone;     
    public Integer getId() {         
        return id;      
    }    
    public void setId(Integer id) {         
        this.id = id;    
    }     
    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 getPhone() {          
        return phone;     
    }  
    public void setPhone(String phone) {        
        this.phone = phone;     
    }  
    @Override  
    public String toString() {        
        return "User{" +                
            "id=" + id +                
            ", userName='" + userName + '\'' +              
            ", passWord='" + passWord + '\'' +               
            ", phone='" + phone + '\'' +               
            '}';      
    }  
}
编写映射文件UserMapper.xml

对User表的增删改查操作

在 resource 文件下创建li.chen.com.mipper 目录,再创建普通文件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="userMapper">

    <!--查询操作 resultType 查询结果给他-->
    <select id="findAll" resultType="user">
        select * from test_user
    </select>

</mapper>

编写核心文件sqlMapConfig.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>

    <!--加载外部properties-->
    <properties resource="jdbc.properties"></properties>

    <!--自定义别名 一定要注意实体路径!-->
    <typeAliases>
        <typeAlias type="com.business.entity.User" alias="user"></typeAlias>
    </typeAliases>

    <!--配置数据源环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>

            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件-->
    <mappers>
        <mapper resource="li.chen.com.mapper\UserMapper.xml"/>
    </mappers>

</configuration>
编写dao层(原先的测试类)
package com.business.dao;

import com.business.entity.User;

import java.io.IOException;
import java.util.List;

public interface UserMapper {
    public List<User> findAll() throws IOException;
}
package com.business.dao;

import com.business.entity.User;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserMapperImpl implements UserMapper {
    @Override
    public List<User> findAll() throws IOException {

        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        return userList;
    }
}
编写service层
package com.business.service;

import com.business.dao.UserMapper;
import com.business.dao.UserMapperImpl;
import com.business.entity.User;

import java.io.IOException;
import java.util.List;

public class UserDemo {
    public static void main(String[] args) throws IOException {
        //创建Dao层对象,当前到层实现是手动编写的
        UserMapper userMapper = new UserMapperImpl();
        List<User> all = userMapper.findAll();
        System.out.println(all);
    }
}
代理方式实现(不用写接口的实现)

采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper 接口开发需要遵循以下规范:

1) Mapper.xml文件中的namespace与mapper接口的全限定名相同

2) Mapper接口方法名和Mapper.xml中定义的每个statement的id相同

3) Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同

4) Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
在这里插入图片描述

测试

@Test
public void testProxyDao() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获得MyBatis框架生成的UserMapper接口的实现类
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
}
添加MyBatis的坐标

pom.xml

主要是mysql及mybatis坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>chen.li.com</groupId>
    <artifactId>itheima_mybatis_quick</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>


</project>
编写User实体类
package li.chen.com.business.entity;
public class User {    
    private Integer id;    
    private String userName;    
    private String passWord;    
    private String phone;    
    public Integer getId() {        
        return id;    
    }    
    public void setId(Integer id) {        
        this.id = id;    
    }    
    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 getPhone() {        
        return phone;    
    }    
    public void setPhone(String phone) {        
        this.phone = phone;    
    }    
    @Override    
    public String toString() {        
        return "User{" +                
            "id=" + id +                
            ", userName='" + userName + '\'' +                
            ", passWord='" + passWord + '\'' +                
            ", phone='" + phone + '\'' +                
            '}';    
    }
}
编写映射文件UserMapper.xml (改)

对User表的增删改查操作

在 resource 文件下创建li.chen.com.mipper 目录,再创建普通文件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.business.dao.UserMapper">

    <!--所有-->
    <select id="findAll" resultType="user">
        select * from test_user
    </select>

    <!--根据id进行查询-->
    <select id="findById" parameterType="int" resultType="user">
        select * from test_user where id=#{id}
    </select>


</mapper>
日志文件 log4j.properties(新增)
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout
编写核心文件sqlMapConfig.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>

    <!--加载外部properties-->
    <properties resource="jdbc.properties"></properties>

    <!--自定义别名 一定要注意实体路径!-->
    <typeAliases>
        <typeAlias type="com.business.entity.User" alias="user"></typeAlias>
    </typeAliases>

    <!--配置数据源环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>

            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件-->
    <mappers>
        <mapper resource="li.chen.com.mapper\UserMapper.xml"/>
    </mappers>

</configuration>
编写dao层(改)

删除接口的实现类

package com.business.dao;

import com.business.entity.User;

import java.io.IOException;
import java.util.List;

public interface UserMapper {
    public List<User> findAll() throws IOException;

    public User findById(int id);
}

编写service层(改)
package com.business.service;

import com.business.dao.UserMapper;
import com.business.entity.User;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserDemo {
    public static void main(String[] args) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> all = mapper.findAll();
        System.out.println(all);

        User user = mapper.findById(6);
        System.out.println(user);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岿然如故

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值