1、配置 Mavan 依赖
pom.xml 1 2 3 4 5 6 7 8 9 10 11 12 <dependencies > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.2.2</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 5.1.25</version > </dependency > </dependencies >
在 IntelliJ IDEA 中,还需要配置如下代码,否则不会编译 xml ,导致找不到配置文件 (这里踩坑了)pom.xml 1 2 3 4 5 6 7 8 9 10 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.xml</include > </includes > </resource > </resources > </build >
2、MyBatis 配置文件
mybatis_config.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <?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 ="mysql" > <environment id ="mysql" > <transactionManager type ="JDBC" > </transactionManager > <dataSource type ="POOLED" > <property name ="driver" value ="com.mysql.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql://localhost:3306/store" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="net/crazykid/mapper/categoryMapper.xml" /> <mapper resource ="net/crazykid/mapper/productMapper.xml" /> <package name ="net.crazykid.mapper" /> </mappers > </configuration >
3、pojo类
Category.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package net.crazykid.bean;import java.util.List;public class Category { private String cid; private String cname; private List<Product> products; public Category () {} public Category (String cid, String cname, List<Product> products) { this .cid = cid; this .cname = cname; this .products = products; } public String getCid () { return cid; } public void setCid (String cid) { this .cid = cid; } public String getCname () { return cname; } public void setCname (String cname) { this .cname = cname; } public List<Product> getProducts () { return products; } public void setProducts (List<Product> products) { this .products = products; } @Override public String toString () { return "Category{" + "cid='" + cid + '\'' + ", cname='" + cname + '\'' + ", products=" + products + '}' ; } }
4、Mapper 的编写
1 2 3 4 5 6 7 8 <?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 ="net.crazykid.mapper.categoryMapper" > </mapper >
4.1 插入语句
1 2 3 <insert id ="Insert" parameterType ="net.crazykid.bean.Category" > INSERT INTO category (cid, cname) VALUES (#{cid}, #{cname}); </insert >
4.2 删除语句
注: parameterType
为 String
时,用 #{_parameter}
1 2 3 <delete id ="deleteCategoryById" parameterType ="String" > DELETE FROM category WHERE cid = #{_parameter}; </delete >
4.3 查询语句
查询全部内容
1 2 3 <select id ="selectAllCategory" resultType ="net.crazykid.bean.Category" > SELECT * from category; </select >
根据 ID 查询
1 2 3 <select id ="selectCategoryById" parameterType ="Int" resultType ="net.crazykid.bean.Category" > SELECT * FROM category WHERE cid = #{cid} </select >
多条件查询
1 2 3 4 5 6 7 <select id ="selectMultiCategoryById" resultType ="net.crazykid.bean.Category" > SELECT * FROM category WHERE cid IN <foreach item ="item" index ="index" collection ="list" open ="(" separator ="," close =")" > #{item} </foreach > </select >
动态查询语句
categoryMapper.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <resultMap id ="categoryMap" type ="net.crazykid.bean.Category" > <id column ="cid" property ="cid" /> <result column ="cname" property ="cname" /> <collection column ="cid" property ="products" ofType ="net.crazykid.bean.Product" select ="net.crazykid.mapper.productMapper.selectProductByCId" > </collection > </resultMap > <select id ="selectCategory" parameterType ="java.util.Properties" resultType ="net.crazykid.bean.Category" resultMap ="categoryMap" > SELECT * FROM category <where > <if test ="cid != null" > AND cid = #{cid} </if > <if test ="cname != null" > AND cname = #{cname} </if > </where > </select >
多对一关联查询….(这是另一个类另一个mapper)
1 2 3 4 <resultMap id ="productMap" type ="net.crazykid.bean.Product" extends ="baseMap" > <association column ="cid" property ="category" javaType ="net.crazykid.bean.Category" select ="net.crazykid.mapper.categoryMapper.selectCategoryById" > </association > </resultMap >
5、Mapper 的实现类
categoryMapper.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public interface categoryMapper { void Insert (Category category) ; List<Category> selectAllCategory () ; List<Category> selectCategory (Properties properties) ; void deleteCategoryById (String id) ; List<Category> selectMultiCategoryById (List list) ; @Select ("SELECT * FROM category where cid=#{cid}" ) List<Category> selectAllCategory2 (String cid) ; }
6、测试类
categoryTest.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 public class categoryTest { SqlSessionFactory sessionFactory = null ; InputStream inputStream = null ; @Before public void init () { try { inputStream = Resources.getResourceAsStream("mybatis_config.xml" ); sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } @Test public void testInsert () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); Category category = new Category(); category.setCid("123" ); category.setCname("阔落" ); CategoryMapper.Insert(category); session.commit(); session.close(); } @Test public void testSelectAllCategory () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); List<Category> list = CategoryMapper.selectAllCategory(); System.out.println(list); } @Test public void testSelectCategory () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); Properties properties = new Properties(); properties.setProperty("cid" , "1" ); List<Category> list = CategoryMapper.selectCategory(properties); System.out.println(list); } @Test public void testDeleteCategoryById () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); CategoryMapper.deleteCategoryById("aaa2" ); } @Test public void testSelectMultiCategoryById () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); List li = new ArrayList(); li.add(1 ); li.add(2 ); List<Category> list = CategoryMapper.selectMultiCategoryById(li); System.out.println(list); } @Test public void testSelectAllCategory2 () { SqlSession session = sessionFactory.openSession(); categoryMapper CategoryMapper=session.getMapper(categoryMapper.class); List<Category> list = CategoryMapper.selectAllCategory2("6" ); System.out.println(list); } }
7、整合 Log4j
7.1 导入 Log4j 包
pom.xml 1 2 3 4 5 6 <dependency > <groupId > log4j</groupId > <artifactId > log4j</artifactId > <version > 1.2.17</version > </dependency >
7.2 引入 Log4j
踩坑记录: 必须按照指定的顺序放置标签,如 <setting>
不能 放在 <environments>
或者 <mappers>
的后面,否则会报错!!
mybatis_config.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <configuration > <settings > <setting name ="logImpl" value ="LOG4J" /> </settings > <environments default ="mysql" > ... </environments > <mappers > ... </mappers > </configuration >
7.3 Log4j 的配置文件
log4j.properties 1 2 3 4 5 6 7 8 9 10 11 # 全局日志配置 log4j.rootLogger=ERROR, stdout # 指定Mapper的日志配置 log4j.logger.net.crazykid.mapper.categoryMapper=TRACE # 控制台输出 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n # 对于命名空间为 net.crazykid.mapper.categoryMapper 的 Mapper,日子级别为 Trace # 其余的则为全局配置级别 Error, stdout