Mybatis入门案例

项目包结构

在这里插入图片描述

创建Maven项目

一、添加pom.xml依赖

 <packaging>jar</packaging>

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

二、配置文件:sqlConfig.xml
1.编写约束

<?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">

2.数据库连接

<configuration>
    <!--配置文件-->
    <environments default="mysql">
        <!--配置MySQL环境-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据库的四个基本配置-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/lianxiti"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
   </configuration> 

3.指定映射路径

<!--指定映射文件的位置-->
    <mappers>
        <mapper resource="mapper/BookMapper.xml"></mapper>
    </mappers>

4.log4j.properties配置文件

log4j.rootCategory=debug, CONSOLE, LOGFILE

log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %-30.30c %x - %m\n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %-30.30c %x - %m\n

三、编写实体

private Integer id;
    private String name;
    private String authorName;
    private Integer price;
    private String press;
    //get和set略

四、DAO层
1.创建book的接口文件

 /**
     * 查询所有
     * @return
     */
    List<Book> findAll();

    /**
     * 查询一条
     * @param id
     * @return
     */
    Book findById(Integer id);

    /**
     * 添加
     * @param book
     */
     void insertBook(Book book);

    /**
     * 修改
     * @param book
     */
    void updateBook(Book book);

    /**
     * 删除
     * @param id
     */
    void deleteBook(Integer id);

    /**
     * 根据作者模糊查询
     * @param authorName
     * @return
     */
    List<Book> findByName(String authorName);

2.创建bookMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "heep://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.demo.dao.BookDao">

</mapper>

3.SQL编写

 <!--查询全部-->
    <select id="findAll" resultType="com.mybatis.demo.entity.Book">
        select * from book;
    </select>
    <!--查询单条-->
    <select id="findById" parameterType="int" resultType="com.mybatis.demo.entity.Book">
        select * from book where id=#{id}
    </select>
    <!--模糊查询-->
    <select id="findByName" parameterType="string" resultType="com.mybatis.demo.entity.Book">
        select * from book where authorName like '%${value}%'
    </select>
    <!--添加-->
    <insert id="insertBook" parameterType="com.mybatis.demo.entity.Book">
        insert into book(name,authorName,price,press)values(#{name},#{authorName},#{price},#{press})
    </insert>
    <!--修改-->
    <update id="updateBook" parameterType="com.mybatis.demo.entity.Book">
        update book set name=#{name},authorName=#{authorName},price=#{price},press=#{press} where id=#{id}
    </update>
    <!--删除-->
    <delete id="deleteBook" parameterType="integer">
        delete from book where id=#{id}
    </delete>

五、测试

 private InputStream in;
    private SqlSession sqlSession;
    private BookDao userDao;
    
    @Before//测试前执行
    public void init()throws Exception{
        //1.读取配置文件
        in= Resources.getResourceAsStream("sqlconfig.xml");
        //2.创建SQLSessionFactory工厂
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory=builder.build(in);
        //3.使用工厂生产sqlsession对象
       sqlSession= factory.openSession();
        //4.使用SQLSession创建dao接口的代理对象
      userDao= sqlSession.getMapper(BookDao.class);
    }
    
    @After//用于执行方法后
    public void destroy()throws Exception{
        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }
    
    //查询所有
    @Test
    public void findAll(){
        //5.使用代理对象执行方法
        List<Book> books=userDao.findAll();
        for (Book book:books){
            System.out.println(book);
        }
    }

    //查询一条数据
    @Test
    public void findBook(){
        Book book=userDao.findById(115);
        System.out.println(book);
    }

    //模糊查询
    @Test
    public void findByName(){
       List<Book> books=userDao.findByName("金");
       for (Book book:books){
           System.out.println(book);
       }
    }
    //添加
    @Test
    public void insertBook(){
        Book book=new Book();
        book.setName("早报");
        book.setAuthorName("李四");
        book.setPrice(55);
        book.setPress("湖北出版社");
        userDao.insertBook(book);
    }
    //修改
    @Test
    public void updateBook(){
        Book book=new Book();
        book.setId(115);
        book.setName("早z报");
        book.setAuthorName("李yi四");
        book.setPrice(55);
        book.setPress("湖北出版社");
        userDao.updateBook(book);
    }
    //删除
    @Test
    public void deleteBook(){
        userDao.deleteBook(115);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值