慕課網 mybatis基礎學習
阿新 • • 發佈:2019-01-02
1、Mybatis中SqlSession的作用;
向SQL語句出入引數;
執行SQL語句;
獲取SQL語句執行的結果;
事務的控制;
2、如何得到SqlSession?
通過配置檔案獲取資料庫連線的相關資訊;
通過配置資訊構建SqlSessionFactory;
通過SqlSessionFactory開啟資料庫會話;
1.新增mybatis.jar包
下載地址https://github.com/mybatis/mybatis-3/releases
2.配置檔案
mybatis\mybatis-3-mybatis-3.3.0\src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml
修改:
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/micro_message"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
3.得到SqlSession
//通過配置檔案獲取資料庫連線資訊
Reader reader=Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
//通過配置資訊構建一個SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
//通過SqlSessionFactory開啟一個數據庫對話
SqlSession sqlSession=sqlSessionFactory.openSession();
4.核心配置檔案
mybatis\mybatis-3-mybatis-3.3.0\src\test\java\org\apache\ibatis\submitted\complex_property\User.xml
修改:
<mapper namespace="Message">
<resultMap type="com.imooc.bean.Message" id="MessageResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="COMMAND" jdbcType="VARCHAR" property="command"/>
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
</resultMap>
<select id="queryMessageList" parameterType="long" resultMap="MessageResult">
select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE where 1=1
</select>
5.查詢
public List<Message> queryMessageList(String command,String description){
List<Message> messageList=new ArrayList<Message>();
DBAccess dbAcess=new DBAccess();
SqlSession sqlSession=null;
try {
sqlSession=dbAcess.getSqlSession();
messageList=sqlSession.selectList("Message.queryMessageList");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(sqlSession!=null)
sqlSession.close();
}
return messageList;
}
6.傳遞查詢引數
sqlSession.selectList(引數1,引數2)只能傳遞兩個引數
ONGL表示式(不是mybatis專有,獨立)
<if test="command!=null and !"".equals(command.trim())"> and COMMAND=#{command}</if>
<if test="description!=null and !"".equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
7.除錯日誌 log4j.jar 下載地址http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.17/log4j-1.2.17.zip
配置檔案mybatis\mybatis-3-mybatis-3.3.0\src\test\java\log4j.properties
直接放在src下
修改: log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
1). debug:輸出的級別,console輸出端的名稱
2). 輸出到控制檯
3).佈局
4).輸出格式:%D產生時間,%t執行緒,%p日誌級別,%c日誌列印的類,%m輸出內容,%n換行
5).org.apache:該包下的日誌級別,第一行是針對所有的日誌定義的級別
8.單表刪除
sqlSession.delete("Message.deleteOne",id);
sqlSession.commit();
配置檔案:
<delete id="deleteOne" parameterType="int">
delete from MESSAGE where ID = #{_parameter}
</delete>
9.批量刪除
配置檔案:
<delete id="deleteBatch" parameterType="java.util.List">
delete from MESSAGE where ID in(
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</delete>
10.前端回覆功能
talk.jsp
$.ajax({
url : $("#basePath").val() + "AutoReplyServlet.action",
type : "POST",
dataType : "text",
timeout : 10000,
success : function (data) {
appendDialog("talk_recordboxme","My賬號",content);
appendDialog("talk_recordbox","公眾號",data);
$("#content").val("");
render();
},
data : {"content":content}
});
AutoReplyServlet.java
//設定編碼
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
QueryService queryService = new QueryService();
out.write(queryService.queryByCommand(req.getParameter("content")));
out.flush();
out.close();
11.一對多
在實體類中新增一個集合,例如:list
在配置檔案中配置:
<collection property = "commandContentList" resultMap = "commandContent.content"/>配置一對多
兩個表中都存在ID,執行後字首會去掉,不能分清,所以給一個ID起別名,一般是主表.
12.標籤
where標籤:select <where> (and內容)</where>
sql標籤 <sql id="columns">ID,COMMAND,CONTENT</sql>
引用:select <include refid="columns"/> from MESSAGE
set標籤 : update MESSAGE set (內容) </set>
trim標籤:代替where標籤<trim prefix="where" prefixOverrides="and/or" > (內容)</trim>
代替set標籤<trim prefix="set" suffixOverrides=",">(內容) </trim>
choose標籤:相當於if..else
<choose>
<when test=""></when>
<when test=""></when>
association標籤:子表關聯主表
<association property="command" resultMap="Command.Command"></association>
<otherwise></otherwise>
</choose>
list標籤:<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
12.容易混淆的概念
resultMap(對映id) resultType(型別)結果集中的列名必須和實體類中相同
parameterMap(不推薦使用) parameterType
#{}(?,preparement,有預編譯效果) ${}(直接替換,場景:order by $())
向SQL語句出入引數;
執行SQL語句;
獲取SQL語句執行的結果;
事務的控制;
2、如何得到SqlSession?
通過配置檔案獲取資料庫連線的相關資訊;
通過配置資訊構建SqlSessionFactory;
通過SqlSessionFactory開啟資料庫會話;
1.新增mybatis.jar包
下載地址https://github.com/mybatis/mybatis-3/releases
2.配置檔案
mybatis\mybatis-3-mybatis-3.3.0\src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml
修改:
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/micro_message"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
3.得到SqlSession
//通過配置檔案獲取資料庫連線資訊
Reader reader=Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
//通過配置資訊構建一個SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
//通過SqlSessionFactory開啟一個數據庫對話
SqlSession sqlSession=sqlSessionFactory.openSession();
4.核心配置檔案
mybatis\mybatis-3-mybatis-3.3.0\src\test\java\org\apache\ibatis\submitted\complex_property\User.xml
修改:
<mapper namespace="Message">
<resultMap type="com.imooc.bean.Message" id="MessageResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="COMMAND" jdbcType="VARCHAR" property="command"/>
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
</resultMap>
<select id="queryMessageList" parameterType="long" resultMap="MessageResult">
select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE where 1=1
</select>
5.查詢
public List<Message> queryMessageList(String command,String description){
List<Message> messageList=new ArrayList<Message>();
DBAccess dbAcess=new DBAccess();
SqlSession sqlSession=null;
try {
sqlSession=dbAcess.getSqlSession();
messageList=sqlSession.selectList("Message.queryMessageList");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(sqlSession!=null)
sqlSession.close();
}
return messageList;
}
6.傳遞查詢引數
sqlSession.selectList(引數1,引數2)只能傳遞兩個引數
ONGL表示式(不是mybatis專有,獨立)
<if test="command!=null and !"".equals(command.trim())"> and COMMAND=#{command}</if>
<if test="description!=null and !"".equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
7.除錯日誌 log4j.jar 下載地址http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.17/log4j-1.2.17.zip
配置檔案mybatis\mybatis-3-mybatis-3.3.0\src\test\java\log4j.properties
直接放在src下
修改: log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
1). debug:輸出的級別,console輸出端的名稱
2). 輸出到控制檯
3).佈局
4).輸出格式:%D產生時間,%t執行緒,%p日誌級別,%c日誌列印的類,%m輸出內容,%n換行
5).org.apache:該包下的日誌級別,第一行是針對所有的日誌定義的級別
8.單表刪除
sqlSession.delete("Message.deleteOne",id);
sqlSession.commit();
配置檔案:
<delete id="deleteOne" parameterType="int">
delete from MESSAGE where ID = #{_parameter}
</delete>
9.批量刪除
配置檔案:
<delete id="deleteBatch" parameterType="java.util.List">
delete from MESSAGE where ID in(
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</delete>
10.前端回覆功能
talk.jsp
$.ajax({
url : $("#basePath").val() + "AutoReplyServlet.action",
type : "POST",
dataType : "text",
timeout : 10000,
success : function (data) {
appendDialog("talk_recordboxme","My賬號",content);
appendDialog("talk_recordbox","公眾號",data);
$("#content").val("");
render();
},
data : {"content":content}
});
AutoReplyServlet.java
//設定編碼
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
QueryService queryService = new QueryService();
out.write(queryService.queryByCommand(req.getParameter("content")));
out.flush();
out.close();
11.一對多
在實體類中新增一個集合,例如:list
在配置檔案中配置:
<collection property = "commandContentList" resultMap = "commandContent.content"/>配置一對多
兩個表中都存在ID,執行後字首會去掉,不能分清,所以給一個ID起別名,一般是主表.
12.標籤
where標籤:select <where> (and內容)</where>
sql標籤 <sql id="columns">ID,COMMAND,CONTENT</sql>
引用:select <include refid="columns"/> from MESSAGE
set標籤 : update MESSAGE set (內容) </set>
trim標籤:代替where標籤<trim prefix="where" prefixOverrides="and/or" > (內容)</trim>
代替set標籤<trim prefix="set" suffixOverrides=",">(內容) </trim>
choose標籤:相當於if..else
<choose>
<when test=""></when>
<when test=""></when>
association標籤:子表關聯主表
<association property="command" resultMap="Command.Command"></association>
<otherwise></otherwise>
</choose>
list標籤:<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
12.容易混淆的概念
resultMap(對映id) resultType(型別)結果集中的列名必須和實體類中相同
parameterMap(不推薦使用) parameterType
#{}(?,preparement,有預編譯效果) ${}(直接替換,場景:order by $())
#{} String或基本資料型別#{_parameter}
程式碼上傳 我的資源