1.Mybatis開發(一)
阿新 • • 發佈:2018-03-20
標識 value lec 特殊 ognl 傳遞參數 statement keys dtd
需求:
l 根據Id查詢用戶:傳遞Id
l 根據用戶名進行模糊查詢:傳遞參數:String Username
l 刪除:根據Id進行刪除
l 修改:根據Id進行修改
l 保存
sqlMapConfig.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"> <!-- 配置文件開始,所有配置文件都必須在configuration --> <configuration> <!-- 可以配置多個運行環境,但是每個 SqlSessionFactory 實例只能選擇一個運行環境 一、development:開發模式 二、work:工作模式--> <environments default="development"> <!--id屬性必須和上面的default一樣 --> <environment id="development"> <!-- mybatis事務管理器 ,由jdbc管理--> <transactionManager type="JDBC"/> <!-- mybatis連接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///mybatis01"/> <property name="username" value="root"/> <property name="password" value="moujinling321"/> </dataSource> </environment> </environments> <!-- 引入外部映射文件 --> <mappers> <mapper resource="sqlMap/User.xml"/> </mappers> </configuration>
User:
package domain; import java.util.Date; public class User { private int id; private String username;// 用戶姓名 private String sex;// 性別 private Date birthday;// 生日 private String address;// 地址 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
User.xml:(映射到sqlMapConfig.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"> <!-- MyBatis映射文件的開始標簽 ,所有sql語句全部封裝在mapper裏面 namespace:命名空間 *隔離不同的映射文件,映射文件的唯一標識,可以任意命名 *在接口代理開發中,namespace具有特殊含義,不能任意命名 --> <mapper namespace="test"> <!-- 查詢所有 --> <select id="findAll" resultType="domain.User"> select * from user </select> <!-- 根據Id查詢用戶:傳遞參數類型:integer id mybatis加載sqlMapConfig,加載映射文件User.xml mybatis會把映射文件封裝成一個對象MapperStatement id稱為MapperStatement的唯一標識ID id:sql字段唯一標識,Statement的唯一標識 parameterType:制定傳遞參數類型 resultType:指定結果集映射文件。無論返回的是集合,還是單個對象,結果集映射都是javaBean #{}:占位符? *如果傳遞的參數是基本類型,{}裏可以是任意值 *如果傳遞的參數是pojo,使用ognl表達式獲取。屬性.屬性 --> <select id="findUserByID" parameterType="int" resultType="domain.User"> select * from user where id=#{id} </select> <!-- 根據用戶名進行模糊查詢 ${}:sql語句拼接,原樣把輸入參數封裝到sql語句中。 *如果傳遞參數是基本類型,${}裏面只能是value *如果傳遞參數是pojo,使用ognl表達式獲取 註意:${}是sql語句拼接,有sql語句註入風險,只在模糊查詢時使用 其他情況使用#{} --> <select id="findUserByUsername" resultType="domain.User" parameterType="string"> select * from user where username like ‘%${value}%‘ </select> <!-- 根據id進行刪除 --> <delete id="deleteUserByID" parameterType="int"> delete from user where id=#{id} </delete> <!-- 根據id進行修改 parameterType:制定傳遞參數類型,修改,傳遞pojo類型。 --> <update id="updateUserByID" parameterType="domain.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> <!-- 保存User用戶 (保存後獲取id) 方式二:useGeneratedKeys="true" --> <insert id="insertUser" parameterType="domain.User" useGeneratedKeys="true" keyProperty="id"> <!-- 方式一: selectKey:選擇主鍵返回 keyProperty:指定返回屬性類型 order:由於id是自增的,id是在sql語句執行之後生成的,使用AFTER resultType:指定返回值類型 --> <!-- <selectKey keyProperty="id" order="AFTER" resultType="int"> SELECT LAST_INSERT_ID():得到剛 insert 進去記錄的主鍵值,只適用與自增主鍵 SELECT LAST_INSERT_ID() </selectKey> --> insert into user values(#{id},#{username},#{birthday},#{sex},#{address}) </insert> </mapper>
Main1:
package test; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import domain.User; public class Main1 { SqlSessionFactory sqlSessionFactory=null; @Before public void beforeConf() throws IOException{ // 加載全局配置文件,連接數據庫 String resources = "sqlMapConfig.xml"; // 加載配置文件 InputStream inputStream = Resources.getResourceAsStream(resources); // 獲取工廠 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } /** * 查詢所有 * @throws Exception */ @Test public void findAll() throws Exception { // 加載全局配置文件,連接數據庫 String resources = "sqlMapConfig.xml"; // 加載配置文件 InputStream inputStream = Resources.getResourceAsStream(resources); // 獲取工廠 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //使用工廠創建sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //查詢數據庫 //返回結果是List集合:selectList //selectList如何定位映射文件查詢語句。namespace+id List<User> list = sqlSession.selectList("test.findAll"); System.out.println(list); } /** * 根據ID查詢用戶 * @throws IOException */ @Test public void findUserByID() throws IOException{ String resources="sqlMapConfig.xml"; InputStream inputStream=Resources.getResourceAsStream(resources); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession(); //返回單個對象,使用selectOne方法 //第一個參數:定位查詢語句,namespace+id //第二個參數:傳遞參數,id User user=sqlSession.selectOne("test.findUserByID", 1); System.out.println(user); sqlSession.close(); } /** * 模糊查詢用戶 * @throws IOException */ @Test public void findUserByUsername(){ SqlSession sqlSession=sqlSessionFactory.openSession(); List<User> list=sqlSession.selectList("test.findUserByUsername", "三"); System.out.println(list); } }
Main2:
package test; import static org.hamcrest.CoreMatchers.nullValue; import java.io.IOException; import java.io.InputStream; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import domain.User; public class Main2 { SqlSessionFactory sqlSessionFactory=null; @Before public void beforeConf() throws IOException{ String resources="sqlMapConfig.xml"; InputStream inputStream=Resources.getResourceAsStream(resources); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } //根據id刪除 @Test public void deleteUserByID(){ SqlSession sqlSession=sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUserByID", 26); //提交事務 sqlSession.commit(); sqlSession.close(); } //根據id修改 @Test public void updateUserByID(){ SqlSession sqlSession=sqlSessionFactory.openSession(); User user=new User(); user.setId(16); user.setBirthday(new Date()); user.setAddress("舊金山"); user.setUsername("範冰冰"); sqlSession.update("test.updateUserByID", user); sqlSession.commit(); sqlSession.close(); } //保存用戶 @Test public void insertUser(){ SqlSession sqlSession=sqlSessionFactory.openSession(); User user=new User(); user.setUsername("花果山寨主"); user.setSex("女"); user.setAddress("花果山"); user.setBirthday(new Date()); sqlSession.insert("test.insertUser",user); System.out.println(user.getId()); sqlSession.commit(); System.out.println(user.getId()); sqlSession.close(); } }
1.Mybatis開發(一)