[mybatis]Getting Started
生活随笔
收集整理的這篇文章主要介紹了
[mybatis]Getting Started
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
總體流程
- 1.根據(jù)xml配置文件(全局配置文件)創(chuàng)建一個(gè)SqlSessionFactory對(duì)象
- 2.sql映射文件;配置了每一個(gè)sql,以及sql的封裝規(guī)則等
- 3.將sql映射文件注冊(cè)在全局配置文件中
- 4.寫代碼
- 1)根據(jù)全局配置文件得到SqlSessionFactory
- 2)使用sqlSession工廠,獲取到sqlSession對(duì)象使用他來執(zhí)行增刪改查,一個(gè)sqlSession就是代表和數(shù)據(jù)庫的一次會(huì)話,用完關(guān)閉
- 3)使用sql的唯一標(biāo)志來告訴MyBatis執(zhí)行哪個(gè)sql,sql都是保存在sql映射文件中
maybatis 依賴:
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>x.x.x</version> </dependency>mybatis 配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//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="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><!--將我們寫好的sql映射文件注冊(cè)到全局配置文件中--><mappers><mapper resource="org/mybatis/example/BlogMapper.xml"/></mappers> </configuration>- 根據(jù)xml配置文件(全局配置文件)創(chuàng)建一個(gè)SqlSessionFactoryBuilder對(duì)象
- 獲取sqlSession對(duì)象實(shí)例,能直接執(zhí)行已經(jīng)映射的sql語句
sql映射文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper> try {Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); }finally { sqlSession.close(); }如果數(shù)據(jù)庫和實(shí)體類的數(shù)據(jù)名稱不一樣,可以使用起別名的方法
<select id="selectBlog" resultType="Blog"> select id,last_name lastName,email,gender from Blog where id = #{id} </select>總結(jié)
以上是生活随笔為你收集整理的[mybatis]Getting Started的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win10系统如何提取主题的桌面壁纸如何
- 下一篇: [mybatis]typeHandler