个人知识管理系统Version1.0开发记录(09)

MyBatis初试

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。
 
运用Mybatis框架修改项目,思路如下:
 
1、Oracle SQL Developer,表-》约束条件-》添加主键,实现主键自动增长。
(1)添加主键,
alter table "DYL"."COMPANY" add constraint pk_company primary key("COMPANYID") ;
(2)新建序列,
CREATE SEQUENCE  "DYL"."COMPANY_SEQUENCE"  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER  NOCYCLE ;
(3)触发器-》创建序列中的主键,

begin
execute immediate 'create or replace trigger company_increase '||chr(10)||
' before insert on "DYL"."COMPANY" '||chr(10)||
' for each row '||chr(10)||
'begin '||chr(10)||
' if inserting then '||chr(10)||
' if :NEW."COMPANYID" is null then '||chr(10)||
' select COMPANY_SEQUENCE.nextval into :NEW."COMPANYID" from dual; '||chr(10)||
' end if; '||chr(10)||
' end if; '||chr(10)||
'end;'||chr(10);
end;

个人知识管理系统Version1.0开发记录(09)_第1张图片

 
2、导入mybatis的jar包。
 
3、sqlMap-config.xml配置文件,在src目录下。每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 3 <configuration>
 4 
 5     <typeAliases>
 6         <typeAlias alias="Company" type="com.dyl.entity.Company"/>
 7         <typeAlias alias="Dep" type="com.dyl.entity.Dep"/>
 8         <typeAlias alias="Duty" type="com.dyl.entity.Duty"/>
 9         <typeAlias alias="Staff" type="com.dyl.entity.Staff"/>
10     </typeAliases>
11 
12     <environments default="development">
13         <environment id="development">
14             <transactionManager type="JDBC" />
15             <dataSource type="POOLED">
16                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
17                 <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:PKMS" />
18                 <property name="username" value="DYL" />
19                 <property name="password" value="DYL" />
20             </dataSource>
21         </environment>
22     </environments>
23 
24     <mappers>
25         <mapper resource="com/dyl/entity/xml/Company.xml" />
26 
27     </mappers>
28     
29 </configuration>
View Code

4、POJOs映射,Company.xml,实现数据的增删改查。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="com.dyl.dao.ICompanyDao">
 6 
 7     <select id="selectCompanyById" parameterType="BigDecimal" resultType="Company">
 8         select * from company where companyid = #{id}
 9     </select>
10 
11     <!-- 为了返回list 类型而定义的returnMap -->
12     <resultMap type="Company" id="resultListCompany">
13         <id column="companyId" property="companyId" />
14         <result column="companyName" property="companyName" />
15         <result column="address" property="address" />
16         <result column="telephone" property="telephone" />
17         <result column="leader" property="leader" />
18         <result column="mobilePhone" property="mobilePhone" />
19         <result column="remark" property="remark" />
20     </resultMap>
21 
22     <!-- 返回list 的select 语句,注意 resultMap 的值是指向前面定义好的 -->
23     <select id="selectCompanys" parameterType="string" resultMap="resultListCompany">
24         select * from company where companyName like #{companyName} order by companyid
25     </select>
26 
27     <!--执行增加操作的SQL语句。id和parameterType分别与ICompanyDao接口中的addCompany方法的名字和参数类型一致。以#{name}的形式引用Company参数 
28         的name属性,MyBatis将使用反射读取Company参数的此属性。#{name}中name大小写敏感。引用其他的gender等属性与此一致。useGeneratedKeys设置 
29         为"true",表明要MyBatis获取由数据库自动生成的主键;keyProperty="companyid"指定把获取到的主键值注入到Company的companyid属性 -->
30     <insert id="addCompany" parameterType="Company" useGeneratedKeys="true" keyProperty="companyid">
31         insert into company(companyName,address,telephone,leader,mobilePhone,remark) values
32         (#{companyName},#{address},#{telephone},#{leader},#{mobilePhone},#{remark})
33     </insert>
34 
35     <update id="updateCompany" parameterType="Company">
36         update company set companyName=#{companyName},address=#{address},telephone=#{telephone},
37         leader=#{leader},mobilePhone=#{mobilePhone},remark=#{remark} where companyId=#{companyId}
38     </update>
39 
40     <delete id="deleteCompany" parameterType="BigDecimal">
41         delete from company where companyid=#{id}
42     </delete>
43     
44 </mapper>
View Code

5、namespace="com.dyl.dao.ICompanyDao",修改dao接口,描述参数和SQL语句的返回值。ICompanyDao里面的方法名,对应,Company.xml里面的id。

 1 package com.dyl.dao;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.List;
 5 
 6 import com.dyl.entity.Company;
 7 /**
 8  * Title: 知识管理系统
 9  * Description: 知识管理系统1.0 
10  * Copyright: Copyright (c) 2010-2020 
11  * Company:妖灵科技 
12  * Created on 2014-7-7
13  * @author dyl 
14  * @version 1.0 
15 */ 
16 public interface ICompanyDao {
17     /**
18      * 根据分公司id查找分公司
19      * @param id
20      * @return
21      */
22     public Company selectCompanyById(BigDecimal id);
23     /**
24      * 查找分公司
25      * @param companyName
26      * @return
27      */
28     public List<Company> selectCompanys(String companyName);
29     /**
30      * 增加分公司
31      * @param company
32      */
33     public void addCompany(Company company);
34     /**
35      * 修改分公司
36      * @param company
37      */
38     public void updateCompany(Company company);
39     /**
40      * 删除分公司
41      * @param id
42      */
43     public void deleteCompany(BigDecimal id);
44     
45 }
View Code

6、测试dao接口。

  1 package com.dyl.test;
  2 
  3 import java.io.Reader;
  4 import java.math.BigDecimal;
  5 import java.util.List;
  6 
  7 import org.apache.ibatis.io.Resources;
  8 import org.apache.ibatis.session.SqlSession;
  9 import org.apache.ibatis.session.SqlSessionFactory;
 10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 11 
 12 import com.dyl.dao.ICompanyDao;
 13 import com.dyl.entity.Company;
 14 /**
 15  * 测试类
 16  * Title: 知识管理系统
 17  * Description: 知识管理系统1.0 
 18  * Copyright: Copyright (c) 2010-2020 
 19  * Company:妖灵科技 
 20  * Created on 2014-7-7
 21  * @author dyl 
 22  * @version 1.0
 23  */
 24 public class CompanyXmlTest {
 25     private static SqlSessionFactory sqlSessionFactory;
 26     private static Reader reader;
 27 
 28     static {
 29         try {
 30             reader = Resources.getResourceAsReader("sqlMap-config.xml");
 31             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
 32         } catch (Exception e) {
 33             e.printStackTrace();
 34         }
 35     }
 36 
 37     public static SqlSessionFactory getSession() {
 38         return sqlSessionFactory;
 39     }
 40     
 41     /**
 42      * 查找分公司
 43      * @param companyName
 44      */
 45     public void getCompanyList(String companyName){
 46         SqlSession session = sqlSessionFactory.openSession();
 47         try {
 48             ICompanyDao companyDao=session.getMapper(ICompanyDao.class);           
 49             List<Company> companys = companyDao.selectCompanys(companyName);
 50             for(Company company:companys){
 51                 System.out.println(company.getCompanyId().toString()+","+company.getCompanyName()+","+company.getAddress());
 52             }  
 53         } finally {
 54             session.close();
 55         }
 56     }
 57     
 58     /**
 59      * 测试增加,增加后,必须提交事务,否则不会写入到数据库。
 60      */
 61     public void addCompany(){       
 62         Company company=new Company();
 63         company.setCompanyName("妖灵科技");
 64         company.setAddress("四川成都");
 65         company.setTelephone("028-88888888");
 66         company.setLeader("妖灵");
 67         company.setMobilePhone("18888888888");
 68         company.setRemark("HO");     
 69         SqlSession session = sqlSessionFactory.openSession();
 70         try {
 71             ICompanyDao companyDao=session.getMapper(ICompanyDao.class);
 72             companyDao.addCompany(company);
 73             session.commit();
 74         } finally {
 75             session.close();
 76         }
 77     }
 78     /**
 79      * 先得到公司,然后修改,提交。
 80      */
 81     public void updateCompany(){
 82         SqlSession session = sqlSessionFactory.openSession();
 83         try {            
 84             ICompanyDao companyDao=session.getMapper(ICompanyDao.class);
 85             Company company=companyDao.selectCompanyById(new BigDecimal(2));
 86             company.setAddress("北京");
 87             companyDao.updateCompany(company);
 88             session.commit(); 
 89         } finally {
 90             session.close();
 91         }
 92     }
 93     
 94     /**
 95      * 删除数据,删除一定要commit。
 96      * @param id
 97      */
 98     public void deleteCompany(BigDecimal id){
 99         SqlSession session = sqlSessionFactory.openSession();
100         try {            
101             ICompanyDao companyDao=session.getMapper(ICompanyDao.class);
102             companyDao.deleteCompany(id);
103             session.commit();            
104         } finally {
105             session.close();
106         }
107     }
108     
109     public static void main(String[] args) {
110         SqlSession session = sqlSessionFactory.openSession();
111         try {
112             ICompanyDao companyDao=session.getMapper(ICompanyDao.class);
113             
114 //            // 根据分公司id查找分公司
115 //            Company company=companyDao.selectCompanyById(new BigDecimal(5));
116 //            System.out.println(company.getCompanyName());
117 //            System.out.println(company.getAddress());
118 //            System.out.println();
119             
120 //            // 查找分公司
121 //            CompanyTest companyTest=new CompanyTest();
122 //            companyTest.getCompanyList("%");
123 //            System.out.println();
124             
125             // 增加分公司
126             Company company=new Company();
127             company.setCompanyName("海口分公司");
128             company.setAddress("海南海口");
129             company.setTelephone("0898-88888888");
130             company.setLeader("碧波");
131             company.setMobilePhone("18888888888");
132             company.setRemark("东方夏威夷");     
133             companyDao.addCompany(company);
134             session.commit();
135             System.out.println("当前增加的公司名称为:"+company.getCompanyName());
136             
137 //            // 修改分公司
138 //            Company company=companyDao.selectCompanyById(new BigDecimal(4));
139 //            company.setAddress("天津");
140 //            company.setCompanyName("天津分公司");
141 //            company.setLeader("闻其");
142 //            company.setMobilePhone("18888888888");
143 //            company.setRemark("首都门户");
144 //            company.setTelephone("022-88888888");
145 //            companyDao.updateCompany(company);
146 //            session.commit();
147 //            System.out.println("修改成功");
148             
149 //            // 删除分公司
150 //            companyDao.deleteCompany(new BigDecimal(5));
151 //            session.commit();
152 //            System.out.println("删除成功");
153                     
154         } finally {
155             session.close();
156         }
157     }
158 }
View Code

7、修改dao实现类。

 1 package com.dyl.dao.impl;
 2 
 3 import java.io.Reader;
 4 import java.math.BigDecimal;
 5 import java.util.List;
 6 
 7 import org.apache.ibatis.io.Resources;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactory;
10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
11 
12 import com.dyl.dao.ICompanyDao;
13 import com.dyl.entity.Company;
14 /**
15  * 数据持久层实现类
16  * Title: 知识管理系统
17  * Description: 知识管理系统1.0 
18  * Copyright: Copyright (c) 2010-2020 
19  * Company:妖灵科技 
20  * Created on 2014-7-7
21  * @author dyl 
22  * @version 1.0
23  */
24 public class CompanyDaoImpl implements ICompanyDao{
25     
26     private static SqlSessionFactory sqlSessionFactory;
27     private static Reader reader;
28 
29     static {
30         try {
31             reader = Resources.getResourceAsReader("sqlMap-config.xml");
32             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
33         } catch (Exception e) {
34             e.printStackTrace();
35         }
36     }
37 
38     public static SqlSessionFactory getSession() {
39         return sqlSessionFactory;
40     }
41 
42     SqlSession session = sqlSessionFactory.openSession();
43     ICompanyDao companyDao=session.getMapper(ICompanyDao.class);
44     
45     public Company selectCompanyById(BigDecimal id) {
46         return companyDao.selectCompanyById(id);
47     }
48 
49     public List<Company> selectCompanys(String companyName) {
50         return companyDao.selectCompanys(companyName);
51     }
52 
53     public void addCompany(Company company) {
54         companyDao.addCompany(company);
55         session.commit();
56         session.close();
57     }
58 
59     public void updateCompany(Company company) {
60         companyDao.updateCompany(company);
61         session.commit();
62         session.close();
63     }
64 
65     public void deleteCompany(BigDecimal id) {
66         companyDao.deleteCompany(id);
67         session.commit();
68         session.close();
69     }
70 }
View Code

8、修改工厂。

 1 package com.dyl.util;
 2 
 3 import com.dyl.dao.impl.CompanyDaoImpl;
 4 import com.dyl.dao.impl.CompanyDaoJdbcImpl;
 5 import com.dyl.dao.impl.DepDaoJdbcImpl;
 6 import com.dyl.dao.impl.DutyDaoJdbcImpl;
 7 import com.dyl.dao.impl.OneDsDaoJdbcImpl;
 8 import com.dyl.dao.impl.StaffDaoJdbcImpl;
 9 /**
10  * 工厂设计模式:为调用者提供符合接口要求的对象,方便我们以后采用框架技术进行底层数据访问。
11  * Title: 知识管理系统
12  * Description: 知识管理系统1.0 
13  * Copyright: Copyright (c) 2010-2020 
14  * Company:妖灵科技 
15  * Created on 2014-7-7
16  * @author dyl 
17  * @version 1.0
18  */
19 public class Factory {
20     public static Object getInstance(String type) {
21         Object obj = null;
22         if ("IOneDsDAO".equals(type)) {
23             obj = new OneDsDaoJdbcImpl();
24             
25         } else if ("ICompanyDao".equals(type)) {
26             obj = new CompanyDaoImpl();
27             
28         } else if ("IDepDao".equals(type)) {
29             obj = new DepDaoJdbcImpl();
30         } else if ("IDutyDao".equals(type)) {
31             obj = new DutyDaoJdbcImpl();
32         } else if ("IStaffDao".equals(type)) {
33             obj = new StaffDaoJdbcImpl();
34         }
35         return obj;
36     }
37 }
View Code

9、修改service接口。

 1 package com.dyl.service;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.List;
 5 
 6 import com.dyl.entity.Company;
 7 
 8 public interface ICompanyService {
 9     public Company selectCompanyById(BigDecimal id);// 根据分公司id查找分公司
10     
11     public List<Company> selectCompanys(String companyName);// 查找分公司
12     
13     public void addCompany(Company company);// 增加分公司
14     
15     public void updateCompany(Company company);// 修改分公司
16     
17     public void deleteCompany(BigDecimal id);// 删除分公司
18 }
View Code

10、修改service实现类。

 1 package com.dyl.service.impl;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.List;
 5 
 6 import com.dyl.dao.ICompanyDao;
 7 import com.dyl.entity.Company;
 8 import com.dyl.service.ICompanyService;
 9 import com.dyl.util.Factory;
10 
11 public class CompanyServiceImpl implements ICompanyService {
12     
13     ICompanyDao dao=(ICompanyDao) Factory.getInstance("ICompanyDao");
14     
15     public Company selectCompanyById(BigDecimal id) {
16         return dao.selectCompanyById(id);
17     }
18 
19     public List<Company> selectCompanys(String companyName) {
20         return dao.selectCompanys(companyName);
21     }
22 
23     public void addCompany(Company company) {
24         dao.addCompany(company);
25     }
26 
27     public void updateCompany(Company company) {
28         dao.updateCompany(company);
29     }
30     
31     public void deleteCompany(BigDecimal id) {
32         dao.deleteCompany(id);
33     }    
34 }
View Code

11、测试service实现类。

 1 package com.dyl.test;
 2 
 3 import java.util.List;
 4 
 5 import com.dyl.entity.Company;
 6 import com.dyl.service.ICompanyService;
 7 import com.dyl.service.impl.CompanyServiceImpl;
 8 
 9 public class CompanyServiceImplTest {
10     public static void main(String[] args) {
11         ICompanyService cs=new CompanyServiceImpl();
12         List<Company>companys=cs.selectCompanys("%");
13         System.out.println(companys.size());
14         for(Company company:companys){
15             System.out.println(company.getCompanyId().toString()+","+company.getCompanyName()+","+company.getAddress());
16         }
17     }
18 }
View Code

12、工程结构图如下。

个人知识管理系统Version1.0开发记录(09)_第2张图片

我们接下来需要完成:(1)修改控制层和显示层。(2)分页。(3)动态sql。(4)修改dep、duty、staff。(5)多表关联数据查询。OK,我们下次见。

你可能感兴趣的:(version)