1. 程式人生 > >mybatis環境搭建,對錶進行增刪改查(通過id,查詢所有行(list返回),通過兩個關鍵字進行查詢)

mybatis環境搭建,對錶進行增刪改查(通過id,查詢所有行(list返回),通過兩個關鍵字進行查詢)

搭建mybatis 開發環境

1.    引入jar包

Mybatis 3.2.2.jar    ojdbc5.jar    log4j-1.2.17.jar(列印日誌,可以看到mybatis的具體實現)

2.    為mybatis 設定執行環境(通過配置檔案)

mybatis-config.xml 

3.    Mybatis 的核心類

SqlSessionFactoryBuilder : 負責載入mybatis-config.xml

SQLSessionFactory  負責構建SQLSession

SqlSession:       “一次資料庫會話”,包含了多次資料庫訪問操作,相當於jdbc裡的connection

4 第一個mybatis程式

1、 新建表和實體類

2、 定義dao介面

3、 通過對映表和對映檔案實現dao介面

       <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTDMapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="first.MessageDao">

<!-- namespace="first.MessageDao"表示實現那個介面

 -->

   <insert id="insertMessage" parameterType="first.Message">

      <!--id="insertMessage"實現那個方法   parameterType="first.Message" 所帶的引數是那個型別的  -->

      <!-- 注意插入動作時,物件的主鍵必須得寫,但是沒有賦予,我們需要從資料庫中得到關聯的主鍵然後進行賦值 -->

      <!-- <selectKeyresultType="java.lang.Integer" keyProperty="

物件的主鍵(id)屬性名" order="BEFORE"></selectKey>

查詢主鍵     resultType 主鍵型別   order="BEFORE" 表示在插入資料之前進行查詢

       -->

      insert intoMessage(id,command,description,content) values(#{id},#{command},#{description},#{content})

      <!-- SQL語句賦值採用#{屬性名} -->

   </insert>

</mapper>

       4.將對映檔案配置到mybatis-config.xml檔案中(通知mybatis,有這個檔案)

   <mappers>

      <mapper resource="first/MessageDaoImpl.xml"/>

      <!-- 通知mybatissrc進行寫 -->

   </mappers>

4. 編寫測試類

(1)    首先讀取mybatis配置檔案   

      Reader reader=null;

      try {

        reader = Resources.getResourceAsReader("mybatis-config.xml");

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

    }

(2)    然後使用讀取到的配置檔案構建會話工廠

              SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder();

SqlSessionFactory sf =ssfb.build(reader);

(3)    開啟一個會話

  SqlSession session = sf.openSession();

(4)    得到mybatis為我們建立的介面的實現類,這樣我們就可以操作實現類完成目標

MessageDao dao = session.getMapper(MessageDao.class);

(5)    呼叫實現類的方法進行實現

最後事物提交事物關閉session.commit();

    session.close();

5

查詢功能

<select id=”介面定義的方法名” paramaterType=”方法引數的型別” resuType=”方法返回值型別,要用全類名”>

</select>

注意:mybatis 會自動將結果集中的資料封裝成指定返回值型別的物件。封裝是,將結果的欄位值設定到物件的相應屬性裡,要求結果欄位名和物件的屬性名保持一致

6、更新操作    --mapper檔案寫法

Dao中的介面是   public voidupdataMessage(Message m)

   <update id="updateMessage"         parameterType="first.Message">

      update message setcommand=#{command},description=#{description},content=#{content} where id=#{id}

</update>

注意:updateinsert ,delete操作完成後要進行提交 session.commit()然後在進行關閉操做session.close()

6、刪除操作

Dao中的介面是   public voiddeleteMessage(int id)

7、詢表中所有的元素

Dao中的介面是public List<Message> queryMessage();

<!-- 查詢所有返回List集合 id 為方法名, resultType="first.Message"集合中一個元素的全限定名-->

   <select id="queryMessage" resultType="first.Message">

      select * from message

   </select>

8、使用兩個引數進行對資料的查詢

<!-- 使用兩個關鍵字進行資料的查詢在宣告介面時我們需要這樣設定

      public MessagequeryMessageByCommend(@Param(value="command")Stringcommand,@Param(value="description")String description);

使用@Param(value="command")進行對後面的形參進行定義,從而可以使得下面的select 語句

       command=#{command} anddescription=#{description}

如果不是這樣的話那麼無法識別報錯

    -->

   <select id="queryMessageByCommend" parameterType="java.lang.String" resultType="first.Message">

      select * from message where command=#{command} anddescription=#{description}

   </select>

9

}  如果在sql中包含> <,sql解析時,特殊符號會發生轉義。

}  解決方案1:使用<![CDATA[….]]> 塊

}  解決方案2 :使用轉義字元 &gt; 代替>        &lt;  代替  <

上程式碼:

Message.java

package first;

import java.io.Serializable;

public class Message implements Serializable{
	private int id;
	private String command;
	private String description;
	private String content;
	public Message(int id, String command, String description, String content) {
		//super();
		this.id = id;
		this.command = command;
		this.description = description;
		this.content = content;
	}
	public Message() {
		//super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCommand() {
		return command;
	}
	public void setCommand(String command) {
		this.command = command;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
	
}

方法介面:MessageDao.java
package first;

import java.util.List;

import org.apache.ibatis.annotations.Param;

public interface MessageDao {
	public void insertMessage(Message m);
	
	public Message queryMessageById(int id);
	
	public void updateMessage(Message m);
	
	public void deleteMessage(int id);
	
	public List<Message> queryMessage();
	
	public Message queryMessageByCommend(@Param(value="command")String command,@Param(value="description")String description);
	
}
 

獲取Session物件:MybatisUtil.java

package utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	private static SqlSessionFactory sf=null;
	
	static{
		//得到SQLSession 
		SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder();
		
		Reader reader=null;
		try {
			reader = Resources.getResourceAsReader("mybatis-config.xml");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		sf =ssfb.build(reader);
	}
	
	public static SqlSession getSession()
	{
		SqlSession session=sf.openSession();
		return session;
	}
	
	
	public static void close(SqlSession session)
	{
		if(session!=null){
			session.close();
		}
	}
}


對映檔案:MessageDaoImpl.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="first.MessageDao">
<!-- namespace="first.MessageDao" 表示實現那個介面 -->
	<insert id="insertMessage" parameterType="first.Message">
		<!--id="insertMessage" 實現那個方法    parameterType="first.Message" 所帶的引數是那個型別的  -->
		<!-- 注意插入動作時,物件的主鍵必須得寫,但是沒有賦予,我們需要從資料庫中得到關聯的主鍵然後進行賦值 -->
		<!-- <selectKey resultType="java.lang.Integer" keyProperty="物件的主鍵(id)屬性名" order="BEFORE"></selectKey>
			查詢主鍵     resultType 主鍵型別    order="BEFORE" 表示在插入資料之前進行查詢
		 -->
		insert into Message(id,command,description,content) values(#{id},#{command},#{description},#{content})
		<!-- SQL語句 賦值採用#{屬性名} -->
	</insert>
	
	<select id="queryMessageById" parameterType="java.lang.Integer" resultType="first.Message">
		select id,command,description,content from message where id=#{id}
	</select>
	
	<update id="updateMessage" parameterType="first.Message">
		update message set command=#{command},description=#{description},content=#{content} where id=#{id}
	</update>
	
	<delete id="deleteMessage" parameterType="java.lang.Integer">
		delete from message where id = #{id}
	</delete>
	
	
	<!-- 查詢所有 返回List集合 id 為方法名, resultType="first.Message"集合中一個元素的全限定名-->
	<select id="queryMessage" resultType="first.Message">
		<!--"<![CDATA[  sql  ]]>"  是為了防止sql語句中特殊字元轉義 -->
		<![CDATA[
		select * from message
		]]>
	</select>
	
	<!-- 使用兩個關鍵字進行資料的查詢 在宣告介面時我們需要這樣設定
		public Message queryMessageByCommend(@Param(value="command")String command,@Param(value="description")String description);
	 	使用@Param(value="command")進行對後面的形參進行定義,從而可以使得下面的select 語句
	 	 command=#{command} and description=#{description}
	 	 如果不是這樣的話那麼無法識別報錯
	 -->
	
	
	<select id="queryMessageByCommend" parameterType="java.lang.String" resultType="first.Message">
		select * from message where command=#{command} and description=#{description}
	</select>
	
</mapper>
最後mybatis配置檔案mybatis-config.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" >
<!-- mybatis 的所有配置都必須定義在configureation 標籤裡 -->
<configuration>
	<!-- 配置mybatis 執行環境。如果需要連線多個數據庫,則需要多個environments -->
	<environments default="development">
		<!-- 配置一個mybatis的執行環境,id屬性是這個環境的唯一標識 -->
		<environment id="development">
			<!-- 設定一個mybatis完成資料庫操作是事物的提交策略,type屬性值為JDBC表示用JDBC的方式進行提交 -->
			<transactionManager type="JDBC"></transactionManager>
			<!-- 配置資料庫連線,type為“POOLED” 表示使用mybatis內建連線池-->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://127.0.0.1/myroot"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="first/MessageDaoImpl.xml"/>
		<!-- 通知mybatis -->
	</mappers>
	
	
</configuration>


測試檔案:TestMessageDao.java
package first;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import utils.MybatisUtil;


public class TextMessageDao {
	public static void main(String[] args) {	
		SqlSession session = MybatisUtil.getSession();		
		//得到到的實現類
		MessageDao dao = session.getMapper(MessageDao.class);
		
		/*
		 * 增加資料
		 */
		//呼叫insert 方法完成
//		Message message = new Message();
//		message.setCommand("asasas");
//		message.setContent("111111");
//		message.setDescription("111111111");
//		
//		dao.insertMessage(message);
//		
//		//提交
//		session.commit();
//		
//		session.close();
//		
		/*
		 * 通過ID查詢資料
		 */
		
//		Message me=dao.queryMessageById(3);
//		System.out.println(me.getCommand());
//		System.out.println(me.getContent());
//		System.out.println(me.getDescription());
		
		/*
		 * 更新操作
		 */
		
//		Message me =new Message();
//		me.setId(6);
//		me.setCommand("zhang");
//		me.setDescription("張成功");
//		me.setContent("張徹底成功了");
//		
//		dao.updateMessage(me);
//		session.commit();
//		session.close();
		
		
		/*
		 * 刪除操作
		 */
		
//		dao.deleteMessage(6);
//		
//		session.commit();
//		session.close();
		
		/**
		 * 
		 * list集合進行獲取表中所有的資料
		 */
		
//		List<Message> messages = dao.queryMessage();
//		
//		for(Message message : messages){
//			System.out.println(message.getId());
//			System.out.println(message.getCommand());
//			System.out.println(message.getDescription());
//			System.out.println(message.getContent());
//		}
		
		Message message=dao.queryMessageByCommend("檢視", "精彩內容");
		System.out.println(message.getId());
		System.out.println(message.getCommand());
		System.out.println(message.getDescription());
		System.out.println(message.getContent());
	}
}