Dict.CN 在线词典, 英语学习, 在线翻译 ------------- MyGitee 朱秋贵内科诊所 My腾云code

daotest spring+myibatis

 


*************************main.resources *************************
applicationContext.xml
db.properties
goodsMapper.xml
mybatis-config.xml

goods.sql

pom.xml

 

1、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<!--1 引入属性文件,在配置中占位使用 -->
<context:property-placeholder location="classpath*:db.properties" />

<!--2 配置C3P0数据源 -->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--驱动类名 -->
<property name="driverClass" value="${mysql.driver}" />
<!-- url -->
<property name="jdbcUrl" value="${mysql.url}" />
<!-- 用户名 -->
<property name="user" value="${mysql.uid}" />
<!-- 密码 -->
<property name="password" value="${mysql.pwd}" />
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
<property name="acquireIncrement" value="5"></property>
<!-- 初始连接池大小 -->
<property name="initialPoolSize" value="10"></property>
<!-- 连接池中连接最小个数 -->
<property name="minPoolSize" value="5"></property>
<!-- 连接池中连接最大个数 -->
<property name="maxPoolSize" value="20"></property>
</bean>

<!--3 会话工厂bean sqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="datasource"></property>
<!-- 别名 -->
<property name="typeAliasesPackage" value="entity"></property>
<!-- sql映射文件路径 -->
<property name="mapperLocations" value="classpath*:*Mapper.xml"></property>
<!--mybatis配置文件位置-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>

<!--4 自动扫描对象关系映射 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 指定要自动扫描接口的基础包,实现接口 -->
<property name="basePackage" value="dao"></property>
</bean>

<!--5 声明式事务管理 -->
<!--定义事物管理器,由spring管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--支持注解驱动的事务管理,指定事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!--6 容器自动扫描IOC组件 -->
<context:component-scan base-package="dao"></context:component-scan>

<!--7 aspectj支持自动代理实现AOP功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

 

 

2、db.properties

#mysql jdbc org.mariadb.jdbc.Driver
mysql.driver=org.mariadb.jdbc.Driver
mysql.url=jdbc:mariadb://localhost:3306/gomall?useUnicode=true&characterEncoding=UTF-8
mysql.uid=root
mysql.pwd=root

3、goodsMapper.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="dao.GoodsDao">
<!--id应该是接口中的方法,结果类型如没有配置别名则应该使用全名称 -->
<select id="getAll" resultType="Goods">
SELECT
goods.id,
goods.`name`,
goods.price,
goods.picture
FROM
goods
</select>
</mapper>

 

4、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="cacheEnabled" value="true"/>
<!--设置日志输出的目标-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>

 

 **********************sql****************************
5、goods.sql
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `goods`
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`price` decimal(10,2) DEFAULT '0.00',
`picture` varchar(100) DEFAULT 'default.jpg',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', 'G7 中原G7三合一浓醇咖啡固体饮料1200', '66.50', '1.jpg');
INSERT INTO `goods` VALUES ('2', '百草味东北松子200gx2袋 坚果炒货零', '42.90', '2.jpg');
INSERT INTO `goods` VALUES ('3', '奈津香 桂圆干500gx2袋莆田特产5A桂', '39.90', '3.jpg');
INSERT INTO `goods` VALUES ('4', '益达尊享护齿装草本40粒+冰柠40粒+西', '25.90', '4.jpg');
INSERT INTO `goods` VALUES ('5', '猴坑茶业2016新茶原产地手工太平猴魁特', '168.00', '5.jpg');
INSERT INTO `goods` VALUES ('6', '嘻鱿记 休闲零食 麻辣香辣奶香炭烧 5种', '39.80', '6.jpg');
INSERT INTO `goods` VALUES ('7', '荣业鸿福五分瘦腊肠 香港土特产香肠腊味', '126.80', '7.jpg');
INSERT INTO `goods` VALUES ('8', '蓓琳娜(BELLINA)3L PDO特级初榨橄榄油', '178.00', '8.jpg');
INSERT INTO `goods` VALUES ('10', '荣业鸿福五分瘦腊肠 香港土特产香肠腊味', '30.60', '9.jpg');



6、


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>testdb</groupId>
<artifactId>testdbhaha</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--log4j日志包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<!-- JUnit单元测试工具 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
<!--Spring框架核心库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- aspectJ AOP 织入器 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>

<!--mybatis-spring适配器 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--Spring java数据库访问包,在本例中主要用于提供数据源 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--mysql数据库驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>-->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.5.2</version>
</dependency>
<!-- mybatis ORM框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--c3p0 连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>
</project>

 

 

*********************************************************

*************************main.java *************************

java =>controller、dao、enity、service/impl

    entity:Goods
    dao:GoodsDao
    service/impl:IGoodsService
    service:GoodsService
    controller:GoodsController
  7、Goods
  package entity;/**
  * @author: z
  * @Date: 2019/12/24 16:53
  */

  /**
  * @program: testdbhaha
  *
  * @description:
  *
  * @author: Z
  *
  * @Date: 2019/12/24 16:53
  */

  import java.io.Serializable;
  import java.math.BigDecimal;

  /**
  * 商品POJO
  */
  public class Goods implements Serializable {
  private int id;
  private String name;
  private BigDecimal price;
  private String picture;

  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 BigDecimal getPrice() {
    return price;
  }

  public void setPrice(BigDecimal price) {
    this.price = price;
  }

  public String getPicture() {
    return picture;
  }

  public void setPicture(String picture) {
    this.picture = picture;
  }

  @Override
  public String toString() {
    return "Goods{" +
    "id=" + id +
    ", name='" + name + '\'' +
    ", price=" + price +
    ", picture='" + picture + '\'' +
    '}';
  }
  }

  8、GoodsDao
  package dao;

  import entity.Goods;
  import org.apache.ibatis.annotations.Param;

  import java.util.List;

  /**
  * @author: z
  * @Date: 2019/12/24 17:05
  */
  public interface GoodsDao {
  /**获得所有商品*/
  public List<Goods> getAll();
  }

  9、GoodsService

  package service.impl;/**
  * @author: z
  * @Date: 2019/12/25 9:55
  */

  import dao.GoodsDao;
  import entity.Goods;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import service.IGoodsService;

  import java.util.List;

  /**
  * @program: testdbhaha
  *
  * @description:
  *
  * @author: Z
  *
  * @Date: 2019/12/25 9:55
  */
  @Service
  public class GoodsService implements IGoodsService {
  @Autowired
  GoodsDao dao;
    public List<Goods> getAll()
    {
      return dao.getAll();
    }
  }

  10、IGoodsService
  package service;

  import entity.Goods;

  import java.util.List;

  /**
  * @author: z
  * @Date: 2019/12/25 9:53
  */
  public interface IGoodsService {
    public List<Goods> getAll();
  }

  11、GoodsController
  package controller;/**
  * @author: Z
  * @Date: 2019/12/25 11:16
  */

  import entity.Goods;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.ResponseBody;
  import service.impl.GoodsService;

  import java.util.List;

  /**
  * @program: testdbhaha
  *
  * @description:
  *
  * @author: z
  *
  * @Date: 2019/12/25 11:16
  */
  @Controller
  @RequestMapping("/goods")
  public class GoodsController {
    @Autowired
    GoodsService goodsService;

    @RequestMapping("/getAll")
    @ResponseBody
    public List<Goods> getAll(){
      return goodsService.getAll();
    }
  }

 

 

 

 

 

 

*************************test.java*************************

test=>controller、dao、service

 

GoodsDaoTest
GoodsServiceTest
GoodsControlllerTest
GoodsControlllerMock


12、GoodsDaoTest

import dao.GoodsDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;//指定bean注入的配置文件
@ContextConfiguration(locations = { "classpath:applicationContext.xml"})
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional()
//@TransactionConfiguration(defaultRollback = true)
@Rollback(true)
public class GoodsDaoTest {

@Autowired
GoodsDao dao;

@Test
public void testGetAll(){
System.out.println(dao.getAll());
}

/* public void testGetAll(){
System.out.println(dao.findNumById());
}*/

/* @Test
public void testDeletes(){
List<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(2);
System.out.println(dao.deleteByIds(ids));
}*/

}


13、GoodsServiceTest

/**
* @author: z
* @Date: 2019/12/25 11:11
*/

import dao.GoodsDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import service.impl.GoodsService;

/**
* @program: testdbhaha
*
* @description:
*
* @author: z
*
* @Date: 2019/12/25 11:11
*/
@ContextConfiguration(locations = { "classpath:applicationContext.xml"})
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional()
//@TransactionConfiguration(defaultRollback = true)
@Rollback(true)
public class GoodsServiceTest {
@Autowired
GoodsService goodsService;
@Test
public void getAll(){
System.out.println(goodsService.getAll());
}

}


14、GoodsControlllerTest

/**
* @author: z
* @Date: 2019/12/25 11:42
*/

import controller.GoodsController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import service.impl.GoodsService;

/**
* @program: testdbhaha
*
* @description:
*
* @author: z
*
* @Date: 2019/12/25 11:42
*/
@ContextConfiguration(locations = { "classpath:applicationContext.xml"})
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional()
//@TransactionConfiguration(defaultRollback = true)
@Rollback(true)
public class GoodsControllerTest {
@Autowired
GoodsController goodsController;
@Test
public void getAll(){
goodsController.getAll();
}
}


15、GoodsControlllerMock


import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

/**
* @program: testdbhaha
*
* @description:
*
* @author: z
*
* @Date: 2019/12/25 14:35
*/
@ContextConfiguration(locations = { "classpath:applicationContext.xml"})
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional()
//@TransactionConfiguration(defaultRollback = true)
@Rollback(true)
@WebAppConfiguration
public class GoodsControlllerMock {
@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setUp(){
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
}

@Test
public void getAll() throws Exception{
mockMvc.perform(
//GET请求
MockMvcRequestBuilders.get("/goods/getAll")
).andDo(MockMvcResultHandlers.print());//输出整个响应结果信息
}
}

 

 

 

*************************web.WEB-INF *************************

   web.xml

 

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/main/resources/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</web-app>

 

daotest__spring-mybatis

JunitSpring-mybatis

 

posted @ 2019-12-24 17:34  cn2024  阅读(176)  评论(0编辑  收藏  举报