1、创建Maven工程
1.1、Fill-->New Maven Project-->Next-->maven-archetype-webapp-->Next-->输入group id和artiface id点击finish完成,这里group id和artiface id就是标识项目唯一坐标的作用,这里不做介绍,然后把工程目录调整下,这样就是个标准的maven工程了。
1.2、编写pom文件,有了maven真的极大的方便了我们构建项目,这里maven帮我们把编写在pom文件中的jar包加入工程中。
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.deng.mybatis</groupId> 5 <artifactId>test1118</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 9 <properties> 10 <spring-version>3.2.0.RELEASE</spring-version> 11 </properties> 12 13 <dependencies> 14 <dependency> 15 <groupId>junit</groupId> 16 <artifactId>junit</artifactId> 17 <version>4.12</version> 18 <scope>test</scope> 19 </dependency> 20 21 <dependency> 22 <groupId>org.mybatis</groupId> 23 <artifactId>mybatis</artifactId> 24 <version>3.3.0</version> 25 </dependency> 26 27 <dependency> 28 <groupId>mysql</groupId> 29 <artifactId>mysql-connector-java</artifactId> 30 <version>5.1.37</version> 31 </dependency> 32 33 <dependency> 34 <groupId>log4j</groupId> 35 <artifactId>log4j</artifactId> 36 <version>1.2.17</version> 37 </dependency> 38 39 <dependency> 40 <groupId>org.springframework</groupId> 41 <artifactId>spring-core</artifactId> 42 <version>${spring-version}</version> 43 </dependency> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-context</artifactId> 47 <version>${spring-version}</version> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-jdbc</artifactId> 52 <version>${spring-version}</version> 53 </dependency> 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-orm</artifactId> 57 <version>${spring-version}</version> 58 </dependency> 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-web</artifactId> 62 <version>${spring-version}</version> 63 </dependency> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-tx</artifactId> 67 <version>${spring-version}</version> 68 </dependency> 69 <dependency> 70 <groupId>org.springframework</groupId> 71 <artifactId>spring-webmvc</artifactId> 72 <version>${spring-version}</version> 73 </dependency> 74 <dependency> 75 <groupId>org.springframework</groupId> 76 <artifactId>spring-test</artifactId> 77 <version>${spring-version}</version> 78 </dependency> 79 <dependency> 80 <groupId>org.springframework</groupId> 81 <artifactId>spring-expression</artifactId> 82 <version>${spring-version}</version> 83 </dependency> 84 <dependency> 85 <groupId>org.springframework</groupId> 86 <artifactId>spring-context-support</artifactId> 87 <version>${spring-version}</version> 88 </dependency> 89 <dependency> 90 <groupId>org.springframework</groupId> 91 <artifactId>spring-beans</artifactId> 92 <version>${spring-version}</version> 93 </dependency> 94 <dependency> 95 <groupId>org.springframework</groupId> 96 <artifactId>spring-aspects</artifactId> 97 <version>${spring-version}</version> 98 </dependency> 99 <dependency> 100 <groupId>org.springframework</groupId> 101 <artifactId>spring-aop</artifactId> 102 <version>${spring-version}</version> 103 </dependency> 104 <dependency> 105 <groupId>org.mybatis</groupId> 106 <artifactId>mybatis-spring</artifactId> 107 <version>1.2.2</version> 108 </dependency> 109 110 <dependency> 111 <groupId>commons-dbcp</groupId> 112 <artifactId>commons-dbcp</artifactId> 113 <version>1.4</version> 114 </dependency> 115 116 <dependency> 117 <groupId>net.sf.ehcache</groupId> 118 <artifactId>ehcache-core</artifactId> 119 <version>2.6.6</version> 120 </dependency> 121 122 <dependency> 123 <groupId>org.mybatis</groupId> 124 <artifactId>mybatis-ehcache</artifactId> 125 <version>1.0.0</version> 126 </dependency> 127 128 </dependencies> 129 <build> 130 <finalName>test1118</finalName> 131 </build> 132 </project>
2、开始整合mybatis和spring
2.1、创建个log4j的配置文件,配置信息直接从mybatis官方文档中拷贝过来
1 log4j.rootLogger=debug, stdout 2 # MyBatis logging configuration... 3 log4j.logger.org.mybatis.example.BlogMapper=TRACE 4 # Console output... 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2.2、新建保存数据库连接的配置文件
1 driverClassName=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8 3 user=root 4 password=123456
2.3、新建applicationContext.xml文件,这个是spring的配置文件,数据库的连接、mapper接口的代理实现类等都交由spring管理。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 8 http://www.springframework.org/schema/tx 9 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd "> 12 13 <!-- 加载properties属性文件 --> 14 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 15 <property name="location" value="classpath:osConfig.properties" /> 16 </bean> 17 18 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 19 <property name="driverClassName" value="${driverClassName}"/> 20 <property name="url" value="${url}"/> 21 <property name="username" value="${user}"/> 22 <property name="password" value="${password}"/> 23 </bean> 24 25 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 26 <property name="configLocation" value="mybatis/SqlMapper.xml" /> 27 <property name="dataSource" ref="dataSource" /> 28 </bean> 29 30 <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 31 <property name="mapperInterface" value="dao.UserMapper" /> 32 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 33 </bean> --> 34 35 <!-- 配置spring自动扫描Mapper接口 --> 36 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 37 <property name="basePackage" value="dao" /> 38 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 39 </bean> 40 41 </beans>
2.4、加上SqlMapper.xml,里面只是给所有的entity包下的实体加了别名。
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!-- <settings> 7 <setting name="cacheEnabled" value="true"/> 8 </settings> --> 9 <typeAliases> 10 <package name="entity"/> 11 </typeAliases> 12 </configuration>
2.5、创建Mapper的映射文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!-- xml方式 --> 6 7 <mapper namespace="dao.UserMapper"> 8 <!-- <cache /> --> 9 <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> 10 11 <sql id="userInfo">id, username, sex, birthday</sql> 12 13 <resultMap type="item" id="itemOrdersMap"> 14 <id property="id" column="id" /> 15 <result property="itemname" column="itemsname" /> 16 <result property="price" column="price" /> 17 <result property="detail" column="detail" /> 18 <result property="pic" column="pic" /> 19 <result property="createTime" column="createtime" /> 20 <collection property="orderdetails" ofType="Orderdetail"> 21 <id property="id" column="detail_id"/> 22 <result property="orderId" column="orders_id" /> 23 <result property="itemId" column="items_id" /> 24 <result property="itemNum" column="items_num" /> 25 </collection> 26 </resultMap> 27 28 <resultMap type="orderdetail" id="orderItemMap"> 29 30 </resultMap> 31 32 <select id="queryUserById" resultType="user" parameterType="int"> 33 select 34 <include refid="userInfo"></include> 35 from user where id = #{id} 36 </select> 37 38 <select id="queryOrderItem" resultType="orderItem" parameterType="int"> 39 select 40 item.id, 41 item.itemsname as itemname, 42 item.price as price, 43 item.detail as detail, 44 detail.id as orderdetailId, 45 detail.orders_id as orderId, 46 detail.items_num as itemNum 47 from items item 48 inner join 49 orderdetail detail 50 on detail.items_id = item.id 51 where item.id = #{id} 52 </select> 53 54 <select id="queryItemOrders" resultMap="itemOrdersMap" parameterType="int" useCache="true"> 55 select 56 item.*, 57 detail.id as detail_id, 58 detail.orders_id, 59 items_num 60 from items item 61 left join 62 orderdetail detail 63 on detail.items_id = item.id 64 where item.id = #{id} 65 </select> 66 67 </mapper>
2.6、创建实体bean,orderdetail对item表这里是一对一的关系,反之是一对多的关系。
1 package entity; 2 3 import java.util.Date; 4 import java.util.List; 5 6 public class Item{ 7 private int id; 8 private String itemname; 9 private Float price; 10 private String detail; 11 private String pic; 12 private Date createTime; 13 private List<Orderdetail> orderdetails; 14 public int getId() { 15 return id; 16 } 17 public void setId(int id) { 18 this.id = id; 19 } 20 public String getItemname() { 21 return itemname; 22 } 23 public void setItemname(String itemname) { 24 this.itemname = itemname; 25 } 26 public Float getPrice() { 27 return price; 28 } 29 public void setPrice(Float price) { 30 this.price = price; 31 } 32 public String getDetail() { 33 return detail; 34 } 35 public void setDetail(String detail) { 36 this.detail = detail; 37 } 38 public String getPic() { 39 return pic; 40 } 41 public void setPic(String pic) { 42 this.pic = pic; 43 } 44 public Date getCreateTime() { 45 return createTime; 46 } 47 public void setCreateTime(Date createTime) { 48 this.createTime = createTime; 49 } 50 public List<Orderdetail> getOrderdetails() { 51 return orderdetails; 52 } 53 public void setOrderdetails(List<Orderdetail> orderdetails) { 54 this.orderdetails = orderdetails; 55 } 56 @Override 57 public String toString() { 58 return "Item [id=" + id + ", itemname=" + itemname + ", price=" + price 59 + ", detail=" + detail + ", pic=" + pic + ", createTime=" 60 + createTime + ", orderdetails=" + orderdetails + "]"; 61 } 62 }
1 package entity; 2 3 public class Orderdetail{ 4 private int id; 5 private int orderId; 6 private int itemId; 7 private int itemNum; 8 private Item item; 9 10 public int getId() { 11 return id; 12 } 13 public void setId(int id) { 14 this.id = id; 15 } 16 public int getOrderId() { 17 return orderId; 18 } 19 public void setOrderId(int orderId) { 20 this.orderId = orderId; 21 } 22 public int getItemId() { 23 return itemId; 24 } 25 public void setItemId(int itemId) { 26 this.itemId = itemId; 27 } 28 public int getItemNum() { 29 return itemNum; 30 } 31 public void setItemNum(int itemNum) { 32 this.itemNum = itemNum; 33 } 34 public Item getItem() { 35 return item; 36 } 37 public void setItem(Item item) { 38 this.item = item; 39 } 40 @Override 41 public String toString() { 42 return "Orderdetail [id=" + id + ", orderId=" + orderId + ", itemId=" 43 + itemId + ", itemNum=" + itemNum + ", item=" + item + "]"; 44 } 45 }
1 package entity; 2 3 public class OrderItem{ 4 private int id; 5 private String itemname; 6 private Float price; 7 private String detail; 8 private int orderdetailId; 9 private int orderId; 10 private int itemNum; 11 12 public int getOrderdetailId() { 13 return orderdetailId; 14 } 15 public void setOrderdetailId(int orderdetailId) { 16 this.orderdetailId = orderdetailId; 17 } 18 public int getOrderId() { 19 return orderId; 20 } 21 public void setOrderId(int orderId) { 22 this.orderId = orderId; 23 } 24 public int getId() { 25 return id; 26 } 27 public void setId(int id) { 28 this.id = id; 29 } 30 public int getItemNum() { 31 return itemNum; 32 } 33 public void setItemNum(int itemNum) { 34 this.itemNum = itemNum; 35 } 36 public String getItemname() { 37 return itemname; 38 } 39 public void setItemname(String itemname) { 40 this.itemname = itemname; 41 } 42 public Float getPrice() { 43 return price; 44 } 45 public void setPrice(Float price) { 46 this.price = price; 47 } 48 public String getDetail() { 49 return detail; 50 } 51 public void setDetail(String detail) { 52 this.detail = detail; 53 } 54 @Override 55 public String toString() { 56 return "OrderItem [id=" + id + ", itemname=" + itemname + ", price=" 57 + price + ", detail=" + detail + ", orderdetailId=" 58 + orderdetailId + ", orderId=" + orderId + ", itemNum=" 59 + itemNum + "]"; 60 } 61 62 }
2.7、创建Mapper接口,这里Mapper接口的实现类由mabatis使用动态代理给我们生成,查询等等操作等其实还是调用了sqlSession的selectOne等等方法。
1 package dao; 2 3 import java.util.List; 4 5 import entity.Item; 6 import entity.OrderItem; 7 import entity.User; 8 9 public interface UserMapper { 10 public User queryUserById(int userid); 11 12 public List<OrderItem> queryOrderItem(int orderDetailId); 13 14 public Item queryItemOrders(int itemId); 15 }
2.8、加上ehcache的配置文件,在UserMapper中加上这行代码可以选择使用哪种缓存<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>,使用ehcache如果要输出日志可能要用到sl4j,用ehcache不知道为什么执行测试方法就不会打印出sql的log信息
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> 3 <diskStore path="java.io.tmpdir"/> 4 5 <defaultCache 6 maxElementsInMemory="3000" 7 eternal="false" 8 timeToIdleSeconds="3600" 9 timeToLiveSeconds="3600" 10 overflowToDisk="true" 11 diskPersistent="false" 12 diskExpiryThreadIntervalSeconds="100" 13 memoryStoreEvictionPolicy="LRU" 14 /> 15 </ehcache>
2.9测试
1 package test1118.dao; 2 3 import java.util.List; 4 5 import org.junit.Before; 6 import org.junit.Test; 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 10 import dao.UserMapper; 11 import entity.Item; 12 import entity.OrderItem; 13 import entity.User; 14 15 public class UserDaoTest { 16 private ApplicationContext context; 17 private UserMapper userMapper; 18 19 @Before 20 public void before() { 21 context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); 22 userMapper = (UserMapper)context.getBean("userMapper"); 23 } 24 25 @Test 26 public void testQueryUserById() { 27 User user = userMapper.queryUserById(2); 28 System.out.println(user); 29 User user2 = userMapper.queryUserById(1); 30 System.out.println(user2); 31 } 32 33 @Test 34 public void testQueryOrderItem() { 35 List<OrderItem> orderItems = userMapper.queryOrderItem(1); 36 for (OrderItem orderItem2 : orderItems) { 37 System.out.println(orderItem2); 38 } 39 } 40 41 @Test 42 public void testQueryItemOrders() { 43 Item itemOrders = userMapper.queryItemOrders(2); 44 System.out.println(itemOrders); 45 Item itemOrders2 = userMapper.queryItemOrders(2); 46 System.out.println(itemOrders2); 47 } 48 49 }