Mybatis的应用,直接访问数据库
1.引入jar包:pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jareny.it.mybatis</groupId> <artifactId>mybatis-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
2.在/mybatis-demo/src/main/resources下创建
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"> <!-- 根标签 --> <configuration> <settings> <!-- 开启延时加载这是总开关 --> <setting name="LazyLoadingEnabled" value="true"/> <!-- 关闭侵入式延时加载:延时加载就从表查询侵入到主表查询 --> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!-- 环境,可以配置多个,default:指定采用哪个环境 --> <environments default="test"> <!-- id:唯一标识 --> <environment id="test"> <!-- 事务管理器,JDBC类型的事务管理器 --> <transactionManager type="JDBC" /> <!-- 数据源,池类型的数据源 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/test??useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/MyMapper.xml" /> <mapper resource="mappers/UserDaoMapper.xml" /> <mapper resource="mappers/ICountryMapper.xml" /> <mapper resource="mappers/ICountryMapper2.xml" /> <mapper resource="mappers/INewsLabelMapper.xml" /> <mapper resource="mappers/INewsLabelMapper2.xml" /> <mapper resource="mappers/INewsLabelMapper3.xml" /> </mappers> </configuration>
3.在/mybatis-demo/src/main/resources下创建
日志配置文件:log4j.properties
log4j.rootLogger=DEBUG,A1 log4j.logger.org.apache=DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n log4j.logger.com.jareny.it.mybatis.dao.ICountryDao=trace,console #log4j.logger.com.jareny.it.mybatis.entity.Country=trace,console
4.创建实体类
com.jareny.it.mybatis.entity.Country
package com.jareny.it.mybatis.entity; import java.util.Set; public class Country { private Integer cid; private String cname; //关联属性 一对多的查询 private Set<Minister> ministers; public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Set<Minister> getMinisters() { return ministers; } public void setMinisters(Set<Minister> ministers) { this.ministers = ministers; } @Override public String toString() { return "Country [cid=" + cid + ", cname=" + cname + ", ministers=" + ministers + "]"; } }
com.jareny.it.mybatis.entity.Country2
package com.jareny.it.mybatis.entity; import java.util.Set; public class Country2 { private Integer cid; private String cname; public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public String toString() { return "Country2 [cid=" + cid + ", cname=" + cname + "]"; } }
com.jareny.it.mybatis.entity.Minister
package com.jareny.it.mybatis.entity; public class Minister { private Integer mid; private String mname; public Integer getMid() { return mid; } public void setMid(Integer mid) { this.mid = mid; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } @Override public String toString() { return "Minister [mid=" + mid + ", mname=" + mname + "]"; } }
com.jareny.it.mybatis.entity.Minister2
package com.jareny.it.mybatis.entity; public class Minister2 { private Integer mid; private String mname; //关联属性 多对一查询 private Country country; public Integer getMid() { return mid; } public void setMid(Integer mid) { this.mid = mid; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String toString() { return "Minister2 [mid=" + mid + ", mname=" + mname + ", country=" + country + "]"; } }
com.jareny.it.mybatis.entity.NewsLabel
package com.jareny.it.mybatis.entity; import java.util.Set; public class NewsLabel { private Integer id; private String name; private Set<NewsLabel> childent; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<NewsLabel> getChildent() { return childent; } public void setChildent(Set<NewsLabel> childent) { this.childent = childent; } @Override public String toString() { return "NewsLabel [id=" + id + ", name=" + name + ", childents=" + childent + "]"; } }
com.jareny.it.mybatis.entity.NewsLabel2
package com.jareny.it.mybatis.entity; import java.util.Set; public class NewsLabel2 { private Integer id; private String name; private Set<NewsLabel2> childents; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<NewsLabel2> getChildents() { return childents; } public void setChildents(Set<NewsLabel2> childents) { this.childents = childents; } @Override public String toString() { return "NewsLabel2 [id=" + id + ", name=" + name + ", childents=" + childents + "]"; } }
com.jareny.it.mybatis.entity.NewsLabel3
package com.jareny.it.mybatis.entity; import java.util.Set; //子目录查询父目录 public class NewsLabel3 { private Integer id; private String name; private NewsLabel3 parent; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public NewsLabel3 getParent() { return parent; } public void setParent(NewsLabel3 parent) { this.parent = parent; } @Override public String toString() { return "NewsLabel3 [id=" + id + ", name=" + name + ", parent=" + parent + "]"; } }
com.jareny.it.mybatis.entity.NewsLabel4
package com.jareny.it.mybatis.entity; import java.util.List; import java.util.Set; //子目录查询父目录 public class NewsLabel4 { private Integer id; private String name; private NewsLabel4 parent; private List<NewsLabel4> childents; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public NewsLabel4 getParent() { return parent; } public void setParent(NewsLabel4 parent) { this.parent = parent; } public List<NewsLabel4> getChildents() { return childents; } public void setChildents(List<NewsLabel4> childents) { this.childents = childents; } @Override public String toString() { return "NewsLabel4 [id=" + id + ", name=" + name + ", parent=" + parent + ", childents=" + childents + "]"; } }
com.jareny.it.mybatis.entity.User
package com.jareny.it.mybatis.entity; import java.text.SimpleDateFormat; import java.util.Date; public class User { private String id; private String userName; private String password; private String name; private Integer age; private Integer sex; private Date birthday; private String created; private String updated; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String toString() { return "User{" + "id='" + id + '\'' + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", name='" + name + '\'' + ", age=" + age + ", sex=" + sex + ", birthday='" + new SimpleDateFormat("yyyy-MM-dd").format(birthday) + '\'' + ", created='" + created + '\'' + ", updated='" + updated + '\'' + '}'; } }
com.jareny.it.mybatis.test.MybatisTest
package com.jareny.it.mybatis.test; import java.io.InputStream; 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 com.jareny.it.mybatis.entity.User; public class MybatisTest { public static void main(String[] args) throws Exception { // 指定全局配置文件 String resource = "mybatis-config.xml"; // 读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); // 构建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); try { // 操作CRUD,第一个参数:指定statement,规则:命名空间+“.”+statementId // 第二个参数:指定传入sql的参数:这里是用户id User user = sqlSession.selectOne("MyMapper.selectUser", 1); System.out.println(user); } finally { sqlSession.close(); } } }
com.jareny.it.mybatis.dao.impl.UserDaoImpl
package com.jareny.it.mybatis.dao.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.jareny.it.mybatis.dao.UserDao; import com.jareny.it.mybatis.entity.User; public class UserDaoImpl implements UserDao { public SqlSession sqlSession; public UserDaoImpl(SqlSession sqlSession) { this.sqlSession = sqlSession; } public User queryUserById(String id) { return this.sqlSession.selectOne("UserDao.queryUserById", id); } public List<User> queryUserAll() { return this.sqlSession.selectList("UserDao.queryUserAll"); } public void insertUser(User user) { this.sqlSession.insert("UserDao.insertUser", user); } public void updateUser(User user) { this.sqlSession.update("UserDao.updateUser", user); } public void deleteUser(String id) { this.sqlSession.delete("UserDao.deleteUser", id); } }
5.创建dao层
package com.jareny.it.mybatis.dao; import com.jareny.it.mybatis.entity.Country; public interface ICountryMapper { Country selectCountryById(Integer cid); }
com.jareny.it.mybatis.dao.ICountryMapper2
package com.jareny.it.mybatis.dao; import com.jareny.it.mybatis.entity.Country; public interface ICountryMapper2 { Country selectCountryById(Integer cid); }
com.jareny.it.mybatis.dao.INewsLabelMapper
package com.jareny.it.mybatis.dao; import java.util.List; import com.jareny.it.mybatis.entity.Country; import com.jareny.it.mybatis.entity.NewsLabel; public interface INewsLabelMapper { List<NewsLabel> selectChildrenByParent(int pid); }
com.jareny.it.mybatis.dao.INewsLabelMapper2
package com.jareny.it.mybatis.dao; import java.util.List; import com.jareny.it.mybatis.entity.Country; import com.jareny.it.mybatis.entity.NewsLabel; import com.jareny.it.mybatis.entity.NewsLabel2; public interface INewsLabelMapper2 { NewsLabel2 selectChildrenById(int id); }
com.jareny.it.mybatis.dao.INewsLabelMapper3
package com.jareny.it.mybatis.dao; import java.util.List; import com.jareny.it.mybatis.entity.Country; import com.jareny.it.mybatis.entity.NewsLabel; import com.jareny.it.mybatis.entity.NewsLabel2; import com.jareny.it.mybatis.entity.NewsLabel3; public interface INewsLabelMapper3 { NewsLabel3 selectChildrenById(int id); }
com.jareny.it.mybatis.dao.UserDao
package com.jareny.it.mybatis.dao; import java.util.List; import com.jareny.it.mybatis.entity.User; public interface UserDao { /** * 根据id查询用户信息 * * @param id * @return */ public User queryUserById(String id); /** * 查询所有用户信息 * * @return */ public List<User> queryUserAll(); /** * 新增用户 * * @param user */ public void insertUser(User user); /** * 更新用户信息 * * @param user */ public void updateUser(User user); /** * 根据id删除用户信息 * * @param id */ public void deleteUser(String id); }
6.创建Mybatis映射文件:/mybatis-demo/src/main/resources/mappers/ICountryMapper.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:命名空间,随便写,一般保证命名空间唯一 ,为了使用接口动态代理,这里必须是接口的全路径名--> <mapper namespace="com.jareny.it.mybatis.dao.ICountryMapper"> <!-- 一对多查询 --> <resultMap type="com.jareny.it.mybatis.entity.Country" id="countryMapper"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="ministers" ofType="com.jareny.it.mybatis.entity.Minister"> <id column="mid" property="mid"/> <result column="mname" property="mname"/> </collection> </resultMap> <!-- 1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收 2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数 --> <select id="selectCountryById" resultMap="countryMapper"> select cid,cname,mid,mname from country ,minister where countryId=cid and cid=#{cid} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/ICountryMapper2.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:命名空间,随便写,一般保证命名空间唯一 ,为了使用接口动态代理,这里必须是接口的全路径名--> <mapper namespace="com.jareny.it.mybatis.dao.ICountryMapper2"> <resultMap type="com.jareny.it.mybatis.entity.Country" id="countryMapper"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="ministers" ofType="com.jareny.it.mybatis.entity.Minister" column="cid" select="selectMiniSterByCountry"> </collection> </resultMap> <!-- 1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收 2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数 --> <select id="selectCountryById" resultMap="countryMapper"> select cid,cname from country where cid=#{cid} </select> <select id="selectMiniSterByCountry" resultType="com.jareny.it.mybatis.entity.Minister"> select mid,mname from minister where countryId=#{cid} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/INewsLabelMapper.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:命名空间,随便写,一般保证命名空间唯一 ,为了使用接口动态代理,这里必须是接口的全路径名--> <mapper namespace="com.jareny.it.mybatis.dao.ICountryMapper2"> <resultMap type="com.jareny.it.mybatis.entity.Country" id="countryMapper"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="ministers" ofType="com.jareny.it.mybatis.entity.Minister" column="cid" select="selectMiniSterByCountry"> </collection> </resultMap> <!-- 1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收 2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数 --> <select id="selectCountryById" resultMap="countryMapper"> select cid,cname from country where cid=#{cid} </select> <select id="selectMiniSterByCountry" resultType="com.jareny.it.mybatis.entity.Minister"> select mid,mname from minister where countryId=#{cid} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/INewsLabelMapper2.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:命名空间,随便写,一般保证命名空间唯一 ,为了使用接口动态代理,这里必须是接口的全路径名--> <mapper namespace="com.jareny.it.mybatis.dao.INewsLabelMapper2"> <!--自关联的递归查询,查询父目录下的所有子目录 --> <resultMap type="com.jareny.it.mybatis.entity.NewsLabel2" id="NewsLabelMapper2"> <id column="id" property="id"/> <result column="name" property="name"/> <collection property="childents" ofType="com.jareny.it.mybatis.entity.NewsLabel2" column="id" select="selectChildrenByParent2"> </collection> </resultMap> <!-- 1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收 2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数 --> <!-- 这里里父目录 --> <select id="selectChildrenById" resultMap="NewsLabelMapper2"> select id,name from newslabel where id=#{id} </select> <!-- 这里里递归 --> <select id="selectChildrenByParent2" resultMap="NewsLabelMapper2"> select id,name from newslabel where pid=#{id} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/INewsLabelMapper3.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:命名空间,随便写,一般保证命名空间唯一 ,为了使用接口动态代理,这里必须是接口的全路径名--> <mapper namespace="com.jareny.it.mybatis.dao.INewsLabelMapper3"> <!--自关联的递归查询,查询子目录的所父目录 --> <resultMap type="com.jareny.it.mybatis.entity.NewsLabel3" id="NewsLabelMapper3"> <id column="id" property="id"/> <result column="name" property="name"/> <association property="parent" javaType="com.jareny.it.mybatis.entity.NewsLabel3" column="pid" select="selectChildrenById" /> </resultMap> <!-- 1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收 2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数 --> <!-- 这里递归查询父目录 --> <select id="selectChildrenById" resultMap="NewsLabelMapper3"> select id,name,pid from newslabel where id=#{id} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/MyMapper.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:命名空间,随便写,一般保证命名空间唯一 --> <mapper namespace="MyMapper"> <!-- statement,内容:sql语句。id:唯一标识,随便写,在同一个命名空间下保持唯一 resultType:sql语句查询结果集的封装类型,tb_user即为数据库中的表 --> <select id="selectUser" resultType="com.jareny.it.mybatis.entity.User"> select * from tb_user where id = #{id} </select> </mapper>
/mybatis-demo/src/main/resources/mappers/UserDaoMapper.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:命名空间,随便写,一般保证命名空间唯一 --> <mapper namespace="com.jareny.it.mybatis.dao.UserDao"> <!-- statement,内容:sql语句。id:唯一标识,随便写,在同一个命名空间下保持唯一 resultType:sql语句查询结果集的封装类型,tb_user即为数据库中的表 --> <!--<select id="queryUserById" resultType="com.jareny.it.mybatis.entity.User">--> <!--select * from tb_user where id = #{id}--> <!--</select>--> <!--使用别名--> <select id="queryUserById" resultType="com.jareny.it.mybatis.entity.User"> select tuser.id as id, tuser.user_name as userName, tuser.password as password, tuser.name as name, tuser.age as age, tuser.birthday as birthday, tuser.sex as sex, tuser.created as created, tuser.updated as updated from tb_user tuser where tuser.id = #{id}; </select> <select id="queryUserAll" resultType="com.jareny.it.mybatis.entity.User"> select * from tb_user; </select> <!--插入数据--> <insert id="insertUser" parameterType="com.jareny.it.mybatis.entity.User"> INSERT INTO tb_user ( user_name, password, name, age, sex, birthday, created, updated ) VALUES ( #{userName}, #{password}, #{name}, #{age}, #{sex}, #{birthday}, now(), now() ); </insert> <update id="updateUser" parameterType="com.jareny.it.mybatis.entity.User"> UPDATE tb_user <trim prefix="set" suffixOverrides=","> <if test="userName!=null">user_name = #{userName},</if> <if test="password!=null">password = #{password},</if> <if test="name!=null">name = #{name},</if> <if test="age!=null">age = #{age},</if> <if test="sex!=null">sex = #{sex},</if> <if test="birthday!=null">birthday = #{birthday},</if> updated = now(), </trim> WHERE (id = #{id}); </update> <delete id="deleteUser"> delete from tb_user where id=#{id} </delete> </mapper>
7. 创建测试类com.jareny.it.test.MybatisTest
package com.jareny.it.test; 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 com.jareny.it.mybatis.dao.ICountryMapper; import com.jareny.it.mybatis.dao.ICountryMapper2; import com.jareny.it.mybatis.dao.INewsLabelMapper; import com.jareny.it.mybatis.dao.INewsLabelMapper2; import com.jareny.it.mybatis.dao.INewsLabelMapper3; import com.jareny.it.mybatis.entity.Country; import com.jareny.it.mybatis.entity.NewsLabel; import com.jareny.it.mybatis.entity.NewsLabel2; import com.jareny.it.mybatis.entity.NewsLabel3; public class MybatisTest { public ICountryMapper countryMapper; public ICountryMapper2 countryMapper2; public INewsLabelMapper newsLabelMapper; public INewsLabelMapper2 newsLabelMapper2; public INewsLabelMapper3 newsLabelMapper3; public SqlSession sqlSession; @Before public void setUp() throws Exception { // mybatis-config.xml String resource = "mybatis-config.xml"; // 读取配置文件 InputStream is = Resources.getResourceAsStream(resource); // 构建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 获取sqlSession sqlSession = sqlSessionFactory.openSession(); this.countryMapper = sqlSession.getMapper(ICountryMapper.class); this.countryMapper2 = sqlSession.getMapper(ICountryMapper2.class); this.newsLabelMapper = sqlSession.getMapper(INewsLabelMapper.class); this.newsLabelMapper2 = sqlSession.getMapper(INewsLabelMapper2.class); this.newsLabelMapper3 = sqlSession.getMapper(INewsLabelMapper3.class); } /** * 这是联表查询的,两张表一起去查询 * <p>Title: testSelectCountryById</p> * <p>Description: </p> * @throws Exception */ @Test public void testSelectCountryById() throws Exception { Country country = this.countryMapper.selectCountryById(2); System.out.println(country.toString()); } /** * 这是延时加载查询,分开一张表一张表查询 * <p>Title: testSelectCountryById2</p> * <p>Description: </p> * @throws Exception */ @Test public void testSelectCountryById2() throws Exception { Country country = this.countryMapper2.selectCountryById(2); System.out.println(country.toString()); } /** * 这里自关联的递归查询 * <p>Title: testSelectCountryById3</p> * <p>Description: </p> * @throws Exception */ @Test public void testNewsLabelMapper() throws Exception { List<NewsLabel> list = this.newsLabelMapper.selectChildrenByParent(4); System.out.println(list.toString()); } /** * 这里自关联的父目录查询子目录 * <p>Title: testSelectCountryById3</p> * <p>Description: </p> * @throws Exception */ @Test public void testNewsLabelMapper2() throws Exception { NewsLabel2 newNsLabel2 = this.newsLabelMapper2.selectChildrenById(2); System.out.println(newNsLabel2.toString()); } /** * 子目录查询父目录 * <p>Title: testSelectCountryById3</p> * <p>Description: </p> * @throws Exception */ @Test public void testNewsLabelMapper3() throws Exception { NewsLabel3 newNsLabel3 = this.newsLabelMapper3.selectChildrenById(7); System.out.println(newNsLabel3.toString()); } }
com.jareny.it.test.UserDaoTest
package com.jareny.it.test; import java.io.InputStream; import java.util.Date; 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 com.jareny.it.mybatis.dao.UserDao; import com.jareny.it.mybatis.entity.User; public class UserDaoTest { public UserDao userDao; public SqlSession sqlSession; @Before public void setUp() throws Exception { // mybatis-config.xml String resource = "mybatis-config.xml"; // 读取配置文件 InputStream is = Resources.getResourceAsStream(resource); // 构建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 获取sqlSession sqlSession = sqlSessionFactory.openSession(); this.userDao = sqlSession.getMapper(UserDao.class); //this.userDao = new UserDaoImpl(sqlSession); } @Test public void queryUserById() throws Exception { System.out.println(this.userDao.queryUserById("1")); } @Test public void queryUserAll() throws Exception { List<User> userList = this.userDao.queryUserAll(); for (User user : userList) { System.out.println(user); } } @Test public void insertUser() throws Exception { User user = new User(); user.setAge(16); user.setBirthday(new Date("1990/09/02")); user.setName("大鹏"); user.setPassword("123456"); user.setSex(1); user.setUserName("evan"); this.userDao.insertUser(user); this.sqlSession.commit(); } @Test public void updateUser() throws Exception { User user = new User(); user.setBirthday(new Date()); user.setName("静鹏"); user.setPassword("654321"); user.setSex(1); user.setUserName("evanjin"); user.setId("1"); this.userDao.updateUser(user); this.sqlSession.commit(); } @Test public void deleteUser() throws Exception { this.userDao.deleteUser("4"); this.sqlSession.commit(); } }
8.运行sql语句 test.sql
/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 80015 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 80015 File Encoding : 65001 Date: 2019-08-05 00:17:55 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for country -- ---------------------------- DROP TABLE IF EXISTS `country`; CREATE TABLE `country` ( `cid` int(5) NOT NULL AUTO_INCREMENT, `cname` varchar(20) NOT NULL, PRIMARY KEY (`cid`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of country -- ---------------------------- INSERT INTO `country` VALUES ('1', 'USA'); INSERT INTO `country` VALUES ('2', 'England'); -- ---------------------------- -- Table structure for course -- ---------------------------- DROP TABLE IF EXISTS `course`; CREATE TABLE `course` ( `cid` int(5) NOT NULL AUTO_INCREMENT, `cname` varchar(30) DEFAULT NULL, PRIMARY KEY (`cid`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- ---------------------------- -- Records of course -- ---------------------------- INSERT INTO `course` VALUES ('1', 'JAVASE'); INSERT INTO `course` VALUES ('2', 'JAVAEE'); INSERT INTO `course` VALUES ('3', 'Android'); -- ---------------------------- -- Table structure for minister -- ---------------------------- DROP TABLE IF EXISTS `minister`; CREATE TABLE `minister` ( `mid` int(5) NOT NULL AUTO_INCREMENT, `mname` varchar(20) NOT NULL, `countryId` int(5) DEFAULT NULL, PRIMARY KEY (`mid`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of minister -- ---------------------------- INSERT INTO `minister` VALUES ('1', 'aaa', '1'); INSERT INTO `minister` VALUES ('2', 'bbb', '1'); INSERT INTO `minister` VALUES ('3', 'ccc', '1'); INSERT INTO `minister` VALUES ('4', 'ddd', '2'); INSERT INTO `minister` VALUES ('5', 'eee', '2'); -- ---------------------------- -- Table structure for newslabel -- ---------------------------- DROP TABLE IF EXISTS `newslabel`; CREATE TABLE `newslabel` ( `id` int(20) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `pid` int(5) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- ---------------------------- -- Records of newslabel -- ---------------------------- INSERT INTO `newslabel` VALUES ('1', '娱乐新闻', '0'); INSERT INTO `newslabel` VALUES ('2', '体育新闻', '0'); INSERT INTO `newslabel` VALUES ('3', 'NBA', '2'); INSERT INTO `newslabel` VALUES ('4', 'CBA', '2'); INSERT INTO `newslabel` VALUES ('5', '火箭', '3'); INSERT INTO `newslabel` VALUES ('6', '湖人', '3'); INSERT INTO `newslabel` VALUES ('7', '东莞银行', '4'); INSERT INTO `newslabel` VALUES ('8', '北京金隅', '4'); INSERT INTO `newslabel` VALUES ('9', '青岛双星', '4'); INSERT INTO `newslabel` VALUES ('10', '港台明星', '1'); INSERT INTO `newslabel` VALUES ('11', '内地明星', '1'); -- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sid` int(11) NOT NULL AUTO_INCREMENT, `sname` varchar(30) DEFAULT NULL, PRIMARY KEY (`sid`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ('1', 'zhangsan'); INSERT INTO `student` VALUES ('2', 'lisi'); INSERT INTO `student` VALUES ('3', 'wangwu'); -- ---------------------------- -- Table structure for stu_cou -- ---------------------------- DROP TABLE IF EXISTS `stu_cou`; CREATE TABLE `stu_cou` ( `id` int(5) NOT NULL AUTO_INCREMENT, `studentId` int(5) NOT NULL, `courseId` int(5) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- ---------------------------- -- Records of stu_cou -- ---------------------------- INSERT INTO `stu_cou` VALUES ('1', '1', '1'); INSERT INTO `stu_cou` VALUES ('2', '1', '2'); INSERT INTO `stu_cou` VALUES ('3', '2', '1'); INSERT INTO `stu_cou` VALUES ('4', '2', '3'); -- ---------------------------- -- Table structure for tb_user -- ---------------------------- DROP TABLE IF EXISTS `tb_user`; CREATE TABLE `tb_user` ( `id` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `user_name` varchar(32) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, `name` varchar(32) DEFAULT NULL, `age` int(10) DEFAULT NULL, `sex` int(2) DEFAULT NULL, `birthday` date DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_user -- ---------------------------- INSERT INTO `tb_user` VALUES ('1', 'aaa', '123456', 'zhangsan', '22', '1', '1990-01-04', '2019-08-04 17:44:22', '2019-08-04 17:44:24');