MyBatis入门2
生活随笔
收集整理的這篇文章主要介紹了
MyBatis入门2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、實現單一查詢
1)核心配置文件:Configuration.xml?
1 <?xml version="1.0" encoding="UTF-8"?>2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">3 <configuration>4 <environments default="development">5 <environment id="development">6 <transactionManager type="JDBC" />7 <!-- 配置數據庫連接信息 -->8 <dataSource type="POOLED">9 <property name="driver" value="com.mysql.jdbc.Driver" /> 10 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> 11 <property name="username" value="root" /> 12 <property name="password" value="XDP" /> 13 </dataSource> 14 </environment> 15 </environments> 16 17 </configuration>2)定義表所對應的實體類
package me.gacl.domain;/*** @author gacl* users表所對應的實體類*/ public class User {//實體類的屬性和表的字段名稱一一對應private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";} }3)定義操作users表的sql映射文件userMapper.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,namespace的值習慣上設置成包名+sql映射文件名,這樣就能夠保證namespace的值是唯一的 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后綴)--> <mapper namespace="me.gacl.mapping.userMapper"><!-- 在select標簽中編寫查詢的SQL語句, 設置select標簽的id屬性為getUser,id屬性值必須是唯一的,不能夠重復使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型resultType="me.gacl.domain.User"就表示將查詢結果封裝成一個User類的對象返回User類就是users表所對應的實體類--><!-- 根據id查詢得到一個user對象--><select id="getUser" parameterType="int" resultType="me.gacl.domain.User">select * from users where id=#{id}</select> </mapper>4)在conf.xml文件中注冊userMapper.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><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/mybatis" /><property name="username" value="root" /><property name="password" value="XDP" /></dataSource></environment></environments><mappers><!-- 注冊userMapper.xml文件, userMapper.xml位于me.gacl.mapping這個包下,所以resource寫成me/gacl/mapping/userMapper.xml--><mapper resource="me/gacl/mapping/userMapper.xml"/></mappers></configuration>5)編寫測試代碼:執行定義的select語句
package me.gacl.test;import java.io.IOException; import java.io.InputStream; import java.io.Reader; import me.gacl.domain.User; 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 Test1 {public static void main(String[] args) throws IOException {//mybatis的配置文件String resource = "conf.xml";//使用類加載器加載mybatis的配置文件(它也加載關聯的映射文件)InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);//構建sqlSession的工廠SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);//使用MyBatis提供的Resources類加載mybatis的配置文件(它也加載關聯的映射文件)//Reader reader = Resources.getResourceAsReader(resource); //構建sqlSession的工廠//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);//創建能執行映射文件中sql的sqlSessionSqlSession session = sessionFactory.openSession();/*** 映射sql的標識字符串,* me.gacl.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值,* getUser是select標簽的id屬性值,通過select標簽的id屬性值就可以找到要執行的SQL*/String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的標識字符串//執行查詢返回一個唯一user對象的sqlUser user = session.selectOne(statement, 1);System.out.println(user);} }二、使用MyBatis對表執行CRUD操作——基于XML的實現
使用到的工具類:
package com.ual.Utils;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 java.io.IOException; import java.io.Reader;public class MybatisUtil {/*** 獲取sessionFactory* @return SqlSessionFactory*/public static SqlSessionFactory getSqlSessionFactory() throws IOException {String resource="Configuration.xml";Reader resourceAsReader = Resources.getResourceAsReader(resource);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsReader);return factory;}/*** 獲取sqlSession* @return SqlSession*/public static SqlSession getSqlSession() throws IOException {return getSqlSessionFactory().openSession();}/*** 獲取SqlSession* @param isAutoCommit* true 表示創建的SqlSession對象在執行完SQL之后會自動提交事務* false 表示創建的SqlSession對象在執行完SQL之后不會自動提交事務,這時就需要我們手動調用sqlSession.commit()提交事務* @return SqlSession*/public static SqlSession getSqlSession(boolean isAutoCommit) throws IOException {return getSqlSessionFactory().openSession(isAutoCommit);}}1.UserMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?> <!--Copyright 2009-2016 the original author or authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.--> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="User"><resultMap type="com.ual.domain.User" id="UserResult"><id column="id" jdbcType="INTEGER" property="id"/><result column="username" jdbcType="VARCHAR" property="username"/><result column="password" jdbcType="VARCHAR" property="password"/></resultMap><!--根據id查詢一個User對象--><select id="getById" parameterType="Integer" resultMap="UserResult">select * from user where id=#{id}</select><!--創建用戶--><insert id="addUser" parameterType="com.ual.domain.User">insert into user(username,password)values (#{username},#{password})</insert><!--刪除用戶--><delete id="deleteUser" parameterType="String">delete from user where username=#{username}</delete><!--查詢全部用戶--><select id="selectAll" resultMap="UserResult">select * from user</select> </mapper>2.dao實現類
package com.ual.dao;import com.ual.Utils.MybatisUtil; import com.ual.domain.User; import org.apache.ibatis.session.SqlSession;import java.util.List;public class UserDaoImpl implements UserDao {SqlSession sqlSession=null;@Overridepublic void selectById(Integer id) {try{sqlSession = MybatisUtil.getSqlSession();User user = sqlSession.selectOne("User.getById",id);System.out.println(user);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void insert(User user) {try{sqlSession = MybatisUtil.getSqlSession(true);sqlSession.insert("User.addUser",user);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void deleteByName(String name) {try{sqlSession = MybatisUtil.getSqlSession(true);sqlSession.insert("User.deleteUser",name);}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}}@Overridepublic void update(User user) {}@Overridepublic List<User> selectAll() {try{sqlSession = MybatisUtil.getSqlSession(true);//查詢到的結果,自動封裝成List<User>return sqlSession.selectList("User.selectAll");}catch (Exception e){e.printStackTrace();}finally {if(sqlSession!=null)sqlSession.close();}return null;} }3.單元測試
package com.ual;import com.ual.dao.MessageDao; import com.ual.dao.UserDaoImpl; import com.ual.domain.User;import java.util.List;public class Test {@org.junit.Testpublic void test(){UserDaoImpl userDao = new UserDaoImpl();userDao.selectById(1);}@org.junit.Testpublic void test2(){User user1 = new User();user1.setUsername("xx");user1.setPassword("1234");UserDaoImpl userDao = new UserDaoImpl();userDao.insert(user1);}@org.junit.Testpublic void test3(){UserDaoImpl userDao = new UserDaoImpl();userDao.deleteByName("xx");}@org.junit.Testpublic void test4(){UserDaoImpl userDao = new UserDaoImpl();List<User> users = userDao.selectAll();for (User u:users) {System.out.println(u);}}}三、使用MyBatis對表執行CRUD操作——基于注解的實現
1.定義sql映射的接口
package com.ual.Mapping;import com.ual.domain.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update;import java.util.List;/*** 定義映射的接口*/ public interface UserMapping {//使用@Insert注解指明方法要執行的SQL@Insert("insert into user(username,password )values(#{username},#{password})")public int add(User user);//使用@Deslete注解指明deleteByName方法要執行的sql@Delete("delete from user where username=#{username}")public int deleteByName(String name);@Update("update user set username=#{username},password=#{password} where id= #{id}")public int update(User user);@Select("select * from user where id =#{id}")public User getById(int id );@Select("select * from user")public List<User> getAll();}2、在conf.xml文件中注冊這個映射接口
<?xml version="1.0" encoding="UTF-8" ?> <!--Copyright 2009-2016 the original author or authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.--> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><settings><setting name="useGeneratedKeys" value="false"/><setting name="useColumnLabel" value="true"/></settings><typeAliases><typeAlias alias="User" type="com.ual.domain.User"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"><property name="" value=""/></transactionManager><dataSource type="UNPOOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql:///mybatis?serverTimezone=GMT%2B8"/><property name="username" value="root"/><property name="password" value="1234"/></dataSource></environment></environments><mappers><mapper resource="User.xml"/><!--注冊UserMapping映射接口--><mapper class="com.ual.Mapping.UserMapping"/></mappers></configuration>3.測試
@org.junit.Testpublic void test5() throws IOException {SqlSession sqlSession = MybatisUtil.getSqlSession(true);//獲得會話后,獲取接口,通過獲取的接口調用里面定義的方法UserMapping mapper = sqlSession.getMapper(UserMapping.class);User user = new User();user.setUsername("wzh");user.setPassword("123o");mapper.add(user);sqlSession.close();}?
轉載于:https://www.cnblogs.com/UalBlog/p/10741222.html
總結
以上是生活随笔為你收集整理的MyBatis入门2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gRPC源码分析(c++)
- 下一篇: Load data local infi