MyBatis入门(一)

2017-12-20  本文已影响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">
<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/test" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        //配置mapper的xml文件
    </mappers>
</configuration>
<?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.gongxm.gongxm.bean">
    <select id="findBookById" parameterType="string" resultType="com.gongxm.bean.Book">
        select * from books where id = #{id}
    </select>
</mapper>
<!-- resource是基于classpath查找的 -->
<mapper resource="mapper/Book.xml" />
    private SqlSessionFactory factory = null;
    
    
    @Before
    public void init() throws IOException {
        // 1.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 2.加载配置文件
        InputStream is = Resources.getResourceAsStream("Configuration.xml");

        // 3.创建SqlSessionFactory对象
        factory = builder.build(is);
    }

    @Test
    public void test1() throws IOException {

        // 4.创建SqlSession对象
        SqlSession session = factory.openSession();

        // 5.使用SqlSession对象执行查询,得到结果
        Book book = session.selectOne("findBookById", "a000Mm1WSnpoSjFIMVF4VE1LWEpKUT09");

        // 6.显示结果
        System.out.println(book);
        // 7.释放资源
        session.close();
    }

<!-- 查询多条数据时, 返回类型只需要写集合中的类型即可 -->
<select id="findBooksByName" parameterType="string" resultType="com.gongxm.bean.Book">
        select * from books where book_name like #{name}
</select>

测试代码:

SqlSession session = factory.openSession();
List<Book> list = session.selectList("findBooksByName","%修真%");
if(list!=null) {
    for (Book book : list) {
        System.out.println(book.getBook_name());
    }
}

还可以这样写:
在Book.xml文件中的内容:

<select id="findBooksByName" parameterType="string" resultType="com.gongxm.bean.Book">
    select * from books where book_name like '%${value}%'
</select>

测试代码:

SqlSession session = factory.openSession();
List<Book> list = session.selectList("findBooksByName","修真");
if(list!=null) {
    for (Book book : list) {
        System.out.println(book.getBook_name());
    }
}

以上两种方式的区别:

 #{xxx} : 表示占位符, 名字可以随便起
 ${value} :  表示字符串连接, 名字必须是value, 不能随便起
<insert id="addBook" parameterType="com.gongxm.bean.Book">
    insert into books (id,book_name,book_link,author,category,collectStatus,cover,shortIntroduce,status)
    values (#{id},#{book_name},#{book_link},#{author},#{category},#{collectStatus},#{cover},#{shortIntroduce},#{status})
</insert>

测试代码:

        Book book = new Book("99886128","gongxm", "http://www.gongxm.com/", "java入门", "java", 0, "http://www.gongxm.com/cover.jpg", "java入门必备神书!", "连载中");
        SqlSession session = factory.openSession();
        session.insert("addBook",book);
        session.commit();//提交事务
        session.close();
<!--  keyProperty对应的是pojo对象中的属性, 
        resultType对应的是pojo对象中的属性的类型,
        order: 
              AFTER在插入数据之后执行这个语句
              BEFOR在插入数据之前执行这个语句,例如使用UUID做id的时候
-->
        <selectKey keyProperty="id" order="AFTER" resultType="int">
            select last_insert_id()  // 获取到当前事务中最后插入数据库的ID
        </selectKey>
    <delete id="deleteBook" parameterType="string">
        delete from books where id=#{id}
    </delete>

测试代码:

        SqlSession session = factory.openSession();
        session.delete("deleteBook", "99886128");
        session.commit();//提交事务
        session.close();
    <update id="updateBook" parameterType="com.gongxm.bean.Book">
        update books set book_name=#{book_name},book_link=#{book_link},author=#{author},
        category=#{category},collectStatus=#{collectStatus},cover=#{cover},
        shortIntroduce=#{shortIntroduce},status=#{status} where id=#{id}
    </update>

测试代码:

        Book book = new Book("99886128","gongxm2", "http://www.gongxm.com2/", "java入门2", "java2",1, "http://www.gongxm.com/cover2.jpg", "java入门必备神书2!", "完本");
        SqlSession session = factory.openSession();
        session.update("updateBook", book);
        session.commit();//提交事务
        session.close();
1.Book.xml中的namespace必须是接口的全类名:
<mapper namespace="com.gongxm.dao.BookDao">
2.id必须跟接口中的方法名相同:
 <select id="findBookById" ...
3.parameterType要与接口中的参数类型一致
4.resultType要与接口中的返回值一致

代码示例:

        SqlSession session = factory.openSession();
        BookDao dao = session.getMapper(BookDao.class);
        Book book = dao.findBookById("99886128");
        System.out.println(book);
上一篇下一篇

猜你喜欢

热点阅读