工作日志4-20

来源:互联网 发布:linux上装eclipse 编辑:程序博客网 时间:2024/06/10 01:16

工作日志4-20

研究mybatis+springmvc怎么实现简单增删改查,思路是:首先查询条件我们需要通过View层,用户提交请求用表单接收查询条件,Post提交给对应SpringMVC的Controller;Controller接受参数,调用业务逻辑层(Service层)方法,业务逻辑层对参数进行处理后交给数据访问层(DAO层)在数据库中查询。查询的数据返回Service层,再返回给Controller;然后我们就可以让Controller的Model携带这些数据,转发到一个视图,给用户展示信息!

例子网上找的:

实现具体的增删改查,不去部署Web war的时候我们用Junit单元测试CRUD功能。代码如下:

 applicationContext.xml配置文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd       
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <!-- 引入jdbc.properties -->
    <context:property-placeholderlocation="classpath:jdbc.properties"/>
      
    <!-- 扫描文件  自动将service层和dao层组件注入 -->
    <context:component-scanbase-package="com.clark.service"></context:component-scan>
    <context:component-scanbase-package="com.clark.dao"></context:component-scan>
</beans>

 

jdbc.properties配置文件
1
2
3
4
jdbc_driverClassName=oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@172.30.0.125:1521:oradb01
jdbc_username=settlement
jdbc_password=settlement

 

mybatis-config.xml配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <!-- give a alias for model -->
        <typeAliasalias="goods"type="com.clark.model.Goods"></typeAlias>
    </typeAliases>
    <mappers>
        <!-- <mapper resource="com/clark/model/goodsMapper.xml" /> -->
    </mappers>
</configuration>

 

spring-mybatis.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
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
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">
      
    <beanid="goodsServiceImpl"class="com.clark.service.impl.GoodsServiceImpl">
    </bean>
          
    <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <propertyname="driverClassName">
          <value>${jdbc_driverClassName}</value>
        </property>
        <propertyname="url">
          <value>${jdbc_url}</value>
        </property>
        <propertyname="username">
          <value>${jdbc_username}</value>
        </property>
        <propertyname="password">
          <value>${jdbc_password}</value>
        </property>
        <!-- 连接属性 -->
        <propertyname="connectionProperties">
          <value>clientEncoding=UTF-8</value>
        </property>
    </bean>
       
    <!-- mybatis文件配置,扫描所有mapper文件 -->
      <beanid="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:mybatis-config.xml"
          p:mapperLocations="classpath:mapper/*.xml"/><!-- configLocation为mybatis属性 mapperLocations为所有mapper-->
         
    <!-- spring与mybatis整合配置,扫描所有dao.impl -->
        <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"
            p:basePackage="com.clark.dao.impl"
            p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
          
    <!-- 对数据源进行事务管理 -->
        <beanid="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
            p:dataSource-ref="dataSource"/>
</beans>

 

goodsMapper.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="clark">
    <!-- 将db查询出来的结果映射到Model Goods -->
    <resultMaptype="com.clark.model.Goods"id="t_good">
        <idcolumn="id"property="id"/>
        <resultcolumn="cate_id"property="cateId"/>
        <resultcolumn="name"property="name"/>
        <resultcolumn="price"property="price"/>
        <resultcolumn="description"property="description"/>
        <resultcolumn="order_no"property="orderNo"/>
        <resultcolumn="update_time"property="updateTime"/>
    </resultMap>
    <!-- 根据id查询 返回Goods类型  <typeAlias alias="goods" type="com.clark.model.Goods"></typeAlias>-->
    <!--resultMap 和   resultType的使用区别-->
    <selectid="selectGoodById"parameterType="int"resultMap="t_good">
        select id,cate_id,name,price,description,order_no,update_time 
        from goods where id = #{id}
    </select>
    <!-- 查询所有Goods 返回resultMap类型-->
    <selectid="selectAllGoods"resultMap="t_good">
        select id,cate_id,name,price,description,order_no,update_time from goods
    </select>
    <!-- 指定parameterType=map 其中map的形式为Map<String,PageBean> map-->
    <selectid="selectGoodsByPage"resultMap="t_good"parameterType="map">
        <!-- order by id asc是指对查询后的结果进行升序排序 -->
        <![CDATA[ 
            select * from 
            (select g.*,rownum rn from (select * from goods) g where 1=1 and rownum <= #{pageBean.endNumber}) 
            where rn >= #{pageBean.startNumber}
            order by id asc
        ]]>
    </select>
    <!-- 新增Goods 参数类型为Goods-->
    <insertid="insertGood"parameterType="goods">
        insert into goods(id,cate_id,name,price,description,order_no,update_time)  
        values(#{id},#{cateId},#{name},#{price},#{description},#{orderNo},#{updateTime})
    </insert>
    <!-- 更新Goods 参数类型为Goods-->
    <updateid="updateGood"parameterType="goods">
        update goods g 
        set g.name = #{name},g.order_no =#{orderNo}
        where g.id = #{id}
    </update>
    <!-- 删除Goods 参数类型为int-->
    <deleteid="deleteGood"parameterType="int">
        delete from goods g 
        where g.id = #{id}
    </delete>
</mapper>

 

Model ----Goods.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.clark.model;
  
import java.util.Date;
  
public class Goods {
    privateInteger id;
    privateInteger cateId;
    privateString name;
    privatedouble price;
    privateString description;
    privateInteger orderNo;
    privateDate updateTime;
      
    publicGoods(){
          
    }
      
    publicGoods(Integer id, Integer cateId, String name, doubleprice,
            String description, Integer orderNo, Date updateTime) {
        super();
        this.id = id;
        this.cateId = cateId;
        this.name = name;
        this.price = price;
        this.description = description;
        this.orderNo = orderNo;
        this.updateTime = updateTime;
    }
  
  
    publicInteger getId() {
        returnid;
    }
  
  
    publicvoid setId(Integer id) {
        this.id = id;
    }
  
  
    publicInteger getCateId() {
        returncateId;
    }
  
  
    publicvoid setCateId(Integer cateId) {
        this.cateId = cateId;
    }
  
  
    publicString getName() {
        returnname;
    }
  
  
    publicvoid setName(String name) {
        this.name = name;
    }
  
  
    publicdouble getPrice() {
        returnprice;
    }
  
  
    publicvoid setPrice(doubleprice) {
        this.price = price;
    }
  
  
    publicString getDescription() {
        returndescription;
    }
  
  
    publicvoid setDescription(String description) {
        this.description = description;
    }
  
  
    publicInteger getOrderNo() {
        returnorderNo;
    }
  
  
    publicvoid setOrderNo(Integer orderNo) {
        this.orderNo = orderNo;
    }
  
  
    publicDate getTimeStamp() {
        returnupdateTime;
    }
  
  
    publicvoid setTimeStamp(Date updateTime) {
        this.updateTime = updateTime;
    }
  
  
    @Override
    publicString toString() {
        return"[goods include:Id="+this.getId()+",name="+this.getName()+
                ",orderNo="+this.getOrderNo()+",cateId="+this.getCateId()+
                ",updateTime="+this.getTimeStamp()+"]";
    }
}

 

PageBean.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
package com.clark.util;
//模拟的一个分页对象PageBean
public class PageBean {
    //开始数
    privateInteger startNumber;
    //结束数
    privateInteger endNumber;
      
    publicPageBean(){
          
    }
    publicPageBean(Integer startNumber, Integer endNumber) {
        super();
        this.startNumber = startNumber;
        this.endNumber = endNumber;
    }
    publicInteger getStartNumber() {
        returnstartNumber;
    }
    publicvoid setStartNumber(Integer startNumber) {
        this.startNumber = startNumber;
    }
    publicInteger getEndNumber() {
        returnendNumber;
    }
    publicvoid setEndNumber(Integer endNumber) {
        this.endNumber = endNumber;
    }
}

 

GoodsDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.clark.dao;
  
import java.util.List;
import java.util.Map;
  
import com.clark.model.Goods;
import com.clark.util.PageBean;
  
public interface GoodsDao {
      
    publicint insertGoods(Goods goods);
      
    publicint updateGoods(Goods goods);
      
    publicint deleteGoods(Integer id);
      
    publicGoods findGoodById(Integer id);
    //find all
    publicList<Goods> findAllGoods();
      
    publicList<Goods> findGoodsByPage(Map<String,PageBean> map);
      
}

 

GoodsDaoImpl.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
package com.clark.dao.impl;
  
import java.util.List;
import java.util.Map;
  
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
import com.clark.dao.GoodsDao;
import com.clark.model.Goods;
import com.clark.util.PageBean;
@Service
public class GoodsDaoImpl implementsGoodsDao{
    //注意SqlSessionFactory是mybatis操作数据库的session对象
    @Autowired
    privateSqlSessionFactory sessionFactory;
      
    @Override
    publicint insertGoods(Goods goods) {
        //clark--goodsMapper.xml 中命名空间name = clark,insertGood---insert id
        intresult = sessionFactory.openSession().insert("clark.insertGood", goods);
        //mybatis事物需要手动提交,默认为false
        sessionFactory.openSession().commit();
        returnresult;
    }
    @Override
    publicint updateGoods(Goods goods) {
        intresult = sessionFactory.openSession().update("clark.updateGood", goods);
        //mybatis事物需要手动提交,默认为false
        sessionFactory.openSession().commit();
        returnresult;
    }
    @Override
    publicint deleteGoods(Integer id) {
        intresult = sessionFactory.openSession().delete("clark.deleteGood", id);
        //mybatis事物需要手动提交,默认为false
        sessionFactory.openSession().commit();
        returnresult;
    }
    @Override
    publicGoods findGoodById(Integer id) {
        Goods goods = sessionFactory.openSession().selectOne("clark.selectGoodById",id);
        returngoods;
    }
    @Override
    publicList<Goods> findAllGoods() {
        List<Goods> gg = sessionFactory.openSession().selectList("clark.selectAllGoods");
        returngg;
    }
    @Override
    publicList<Goods> findGoodsByPage(Map<String, PageBean> map) {
        List<Goods> gg = sessionFactory.openSession().selectList("clark.selectGoodsByPage",map);
        returngg;
    }
}

 

GoodsService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.clark.service;
  
import java.util.List;
import java.util.Map;
  
import com.clark.model.Goods;
import com.clark.util.PageBean;
  
public interface GoodsService {
    publicint insertGoods(Goods goods);
      
    publicint updateGoods(Goods goods);
      
    publicint deleteGoods(Integer id);
      
    publicGoods findGoodById(Integer id);
    //find all
    publicList<Goods> findAllGoods();
      
    publicList<Goods> findGoodsByPage(Map<String,PageBean> map);   
}

 

GoodsServiceImpl.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
package com.clark.service.impl;
  
import java.util.List;
import java.util.Map;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
import com.clark.dao.GoodsDao;
import com.clark.model.Goods;
import com.clark.service.GoodsService;
import com.clark.util.PageBean;
@Service
public class GoodsServiceImpl implementsGoodsService{
    @Autowired
    privateGoodsDao goodsDao;
    @Override
    publicint insertGoods(Goods goods) {
        returngoodsDao.insertGoods(goods);
    }
    @Override
    publicint updateGoods(Goods goods) {
        returngoodsDao.updateGoods(goods);
    }
    @Override
    publicint deleteGoods(Integer id) {
        returngoodsDao.deleteGoods(id);
    }
    @Override
    publicGoods findGoodById(Integer id) {
        returngoodsDao.findGoodById(id);
    }
    @Override
    publicList<Goods> findAllGoods() {
        returngoodsDao.findAllGoods();
    }
    @Override
    publicList<Goods> findGoodsByPage(Map<String, PageBean> map) {
        returngoodsDao.findGoodsByPage(map);
    }
  
}

 

单元测试类如下:
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
package maven;
  
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
  
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
import com.clark.model.Goods;
import com.clark.service.GoodsService;
import com.clark.util.PageBean;
  
public class GoodsTest {
    privateGoodsService goodsService;
      
    @Before
    publicvoid before(){                                                                   
        @SuppressWarnings("resource")
        ApplicationContext context =new ClassPathXmlApplicationContext(newString[]{"classpath:applicationContext.xml"
                ,"classpath:spring-mybatis.xml"});
        //注意此处的beanName 必须与XXXXServiceImpl implements XXXXService的名字相同,而且第一个字母必须小写,否则找不到bean
        goodsService = (GoodsService) context.getBean("goodsServiceImpl");
    }
    @Test
    publicvoid testFindGoodsById(){
        Goods goods = goodsService.findGoodById(18);
        System.out.println(goods.toString());
    }
    @Test
    publicvoid testFindAllGoods(){
        List<Goods> goods = goodsService.findAllGoods();
        for(Goods goods2 : goods) {
            System.out.println(goods2.toString());
        }
    }
    @Test
    publicvoid testFindGoodsByPage(){
        PageBean pageBean =new PageBean(8,20);
        Map<String,PageBean> map =new HashMap<String,PageBean>();
        map.put("pageBean", pageBean);
        List<Goods> goods = goodsService.findGoodsByPage(map);
        for(Goods goods2 : goods) {
            System.out.println(goods2.toString());
        }
    }
    @Test
    publicvoid testAddGoods(){
        Goods user =new Goods(20,23, "oooo",23.03, "this is one",5, newDate());
        System.out.println("111111111");
        System.out.println(goodsService.insertGoods(user));
    }
    @Test
    publicvoid testUpdateGoods(){
        Goods goods = goodsService.findGoodById(18);
        goods.setName("AOAO");
        goods.setOrderNo(26);
        System.out.println(goodsService.updateGoods(goods));
    }
      
}

 

接着将Mybatis集成SpringMVC中,部署成网页版的小功能实现:
spring-mvc.xml配置如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
      
    <mvc:annotation-driven/>
    <!-- 扫描组件controller -->
    <context:component-scanbase-package="com.clark.controller"/>
    <!-- 配置模型视图添加前后缀 -->
    <beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/jsp/"p:suffix=".jsp"/>
</beans>

 

web.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
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
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
  
<web-app>
  <display-name>Archetype Created Web Application</display-name>
    
  <!-- 读取spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml;
            classpath:spring-mybatis.xml
        </param-value>
    </context-param>
    <!-- 设计路径变量值 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
   
   
    <!-- Spring字符集过滤器 -->
    <filter>
        <filter-name>SpringEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   
    <!-- springMVC核心配置 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
   
    <!-- 错误跳转页面 -->
    <error-page>
        <!-- 路径不正确 -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
</web-app>

 

简单的Controller类如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.clark.controller;
  
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
  
@Controller
@RequestMapping("/")
public class GoodsController {
    @RequestMapping("index")
    publicString index(){
        return"index";
    }
}
 
 

 

 

0 0
原创粉丝点击