MyBatis学习总结(二)---实例
为了对MyBatis有个初步了解,现做一个简单的增、删、改、查实例。了解涉及的文件与相关作用。
MySql创建friends表,以下是表的sql语句
1 DROP TABLE IF EXISTS `friend`; 2 3 CREATE TABLE `friend` ( 4 `id` bigint(20) NOT NULL, 5 `friendName` varchar(50) NOT NULL, 6 `sex` varchar(10) DEFAULT NULL, 7 PRIMARY KEY (`id`) 8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建一个MyBatisDemo工程
本人使用IDEA 2017创建该工程,也可以使用Eclipse创建。创建工程后,新增相关Package,导入相关的jar包。
目录说明:
com.yiming.demo,存放主类main,暂无写代码。
com.yiming.mapper,存放定义Mapper接口及映射文件,如:FriendMapper文件,friendMapper.xml文件。
com.yiming.pojo,存放实体类。
com.yiming.test,存放测试类,主要用于测试CRUD的方法。
com.yiming.untils,存放工具类,本工程只有:SqlSessionFactoryUntils
db.properties,为数据库属性文件。
mybatis-config.xml,为mybatis主要配置文件。
创建及配置db.properties,mybatis-config.xml二个文件
db.properties文件
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.username=root
database.password=123456
mybatis-config.xml文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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> <!--数据库配置文件--> <properties resource="db.properties"/> <!--别名--> <typeAliases> <typeAlias alias="friend" type="com.yiming.pojo.Friend"/> </typeAliases> <!--数据库环境--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${database.driver}"/> <property name="url" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </dataSource> </environment> </environments> <!--映射文件--> <mappers> <mapper resource="com/yiming/mapper/friendMapper.xml"/> </mappers> </configuration>
创建friend表的实体类
Friend实体类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.yiming.pojo; public class Friend { private long id; private String friendName; private String sex; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFriendName() { return friendName; } public void setFriendName(String friendName) { this.friendName = friendName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
创建FriendMapper文件及friendMapper.xml文件
FriendMapper文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.yiming.mapper; import com.yiming.pojo.Friend; import java.util.List; public interface FriendMapper { int inertFriend(Friend friend); int updateFriend(Friend friend); int deleteFriend(Friend friend); Friend getFriend(long id); List<Friend> getAllFrined(String friendName); }
friendMapper.xml映射文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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="com.yiming.mapper.FriendMapper"> <insert id="inertFriend" parameterType="friend"> insert into friend(id,friendName, sex) values(#{id},#{friendName}, #{sex}) </insert> <delete id="deleteFriend" parameterType="long"> delete from friend where id= #{id} </delete> <update id="updateFriend" parameterType="friend"> update friend set friendName = #{friendName}, sex = #{sex} where id= #{id} </update> <select id="getFriend" parameterType="long" resultType="friend"> select id,friendName, sex from friend where id = #{id} </select> <select id="getAllFrined" parameterType="string" resultType="friend"> select id, friendName, sex from friend where friendName like concat('%', #{friendName}, '%') </select> </mapper>
创建SqlSessionFactoryUtils类
SqlSessionFactoryUtils类文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.yiming.untils; 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.InputStream; public class SqlSessionFactoryUtils { private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; private static SqlSessionFactory sqlSessionFactory = null; private SqlSessionFactoryUtils() { } public static SqlSessionFactory getSqlSessionFactory() { synchronized (LOCK) { if (sqlSessionFactory != null) { return sqlSessionFactory; } String resource = "mybatis-config.xml"; InputStream inputStream; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); return null; } return sqlSessionFactory; } } public static SqlSession openSqlSession() { if (sqlSessionFactory == null) { getSqlSessionFactory(); } return sqlSessionFactory.openSession(); } }
创建FriendCRUD测试类
FriendCRUD
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.yiming.test; import com.yiming.mapper.FriendMapper; import com.yiming.pojo.Friend; import com.yiming.untils.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class FriendCRUD { SqlSession session =null; //插入一对象测试 @Test public void insertFriend( ){ session = SqlSessionFactoryUtils.openSqlSession(); Friend friend =new Friend(); friend.setId(1L); friend.setFriendName("zhangsan"); friend.setSex("man"); try{ FriendMapper friendMapper = session.getMapper(FriendMapper.class); friendMapper.inertFriend(friend); session.commit(); }finally { if(session !=null){ session.close(); } } } @Test public void updateFriend(){ session = SqlSessionFactoryUtils.openSqlSession(); Friend friend = new Friend(); friend.setId(1L); friend.setFriendName("zhangsanfeng"); friend.setSex("man"); try{ FriendMapper friendMapper = session.getMapper(FriendMapper.class); friendMapper.updateFriend(friend); session.commit(); }finally { if(session !=null){ session.close(); } } } @Test public void getFriend(){ session = SqlSessionFactoryUtils.openSqlSession(); try{ FriendMapper friendMapper = session.getMapper(FriendMapper.class); Friend friend = friendMapper.getFriend(1L); System.out.print(friend.getFriendName()); }finally { if(session !=null){ session.close(); } } } @Test public void getAllFriend(){ session = SqlSessionFactoryUtils.openSqlSession(); try{ FriendMapper friendMapper = session.getMapper(FriendMapper.class); List<Friend> friendList = friendMapper.getAllFrined("zhangsanfeng"); for(Friend friend : friendList){ System.out.println(friend); } }finally { if(session !=null){ session.close(); } } } @Test public void deleteFriend(){ session = SqlSessionFactoryUtils.openSqlSession(); try{ FriendMapper friendMapper = session.getMapper(FriendMapper.class); friendMapper.deleteFriend(1L); session.commit(); }finally { if(session !=null){ session.close(); } } } }