一、知识点回顾

  1、Mybatis环境搭建(DAO层的实现)(使用maven项目管理工具)

  需要引入的依赖包:

<!-- 单元测试junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>

    核心配置文件:configuration.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>
<properties resource="database.properties"></properties>
<typeAliases>
<package name="cn.tengyu.entity"/>
</typeAliases>
<!--数据库的连接信息-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接属性-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.tengyu.dao"/>
</mappers>
</configuration>

    Mapper.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="cn.tengyu.dao.DeptMapper">
<!--查询记录数-->
<select id="count" resultType="int">
SELECT count(1) as count FROM dept
</select>
<select id="findAll" resultType="Dept">
SELECT * FROM dept
</select>
<select id="findByName" resultType="Dept" parameterType="String">
SELECT * FROM dept WHERE deptname=#{deptname}
</select> <!--查询某部门员工信息-->
<resultMap id="empList" type="Emp">
<id property="empno" column="empno"/>
</resultMap>
<select id="findByDeptName" parameterType="String" resultMap="empList">
SELECT emp.* FROM emp,dept WHERE dept.deptno=emp.deptno
AND deptname like concat ('%',#{detname},'%')
</select>
<!--添加修改部门信息-->
<insert id="addDeptByName" parameterType="string">
INSERT INTO dept(deptname)VALUES (#{deptname})
</insert>
<insert id="addDept" parameterType="Dept">
INSERT INTO dept(deptno,deptname)VALUES (#{deptno},#{deptname})
</insert>
<!--删除部门信息-->
<delete id="delDept" parameterType="int">
DELETE FROM dept WHERE deptno=#{deptno}
</delete>
<!--修改数据-->
<update id="modifyDept" parameterType="string">
UPDATE dept SET deptname=#{newdeptname} WHERE deptname=#{deptname}
</update>
</mapper>

    MybatisUtil.java

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.InputStream; public class MybatisUtil {
static SqlSessionFactory factory;
static SqlSession sqlSession; /**
* 初始化SqlSessionFactory对象
*/
static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 创建SqlSession对象
*
* @return
*/
public static SqlSession createSqlSession() {
sqlSession = factory.openSession(false);
return sqlSession;
} public static void closeSqlSession(SqlSession sqlSession) {
if (sqlSession != null) {
sqlSession.close();
}
}
}

    测试(使用mybatis实现增删改查)

private static Logger logger = Logger.getLogger(DeptMapperTest.class);
@Test
public void getCount(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
int count = sqlSession.selectOne("cn.tengyu.dao.DeptMapper.count");
logger.debug("部门表总记录数:"+count);
sqlSession.close();
}
@Test
public void findAll(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
List<Dept> depts = sqlSession.selectList("cn.tengyu.dao.DeptMapper.findAll");
for (Dept dept :depts) {
logger.debug("编号:"+dept.getDeptno()+"\t名称:"+dept.getDeptname());
}
sqlSession.close();
}
@Test
public void findByName(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
try {
Dept dept = sqlSession.getMapper(DeptMapper.class).findByName("公关部");
logger.debug("编号:"+dept.getDeptno()+"\t名称:"+dept.getDeptname());
sqlSession.close();
} catch (Exception e) {
logger.debug("查询结果为空!!!");
e.printStackTrace();
}
} @Test
public void findByDeptName(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
List<Emp> emps = sqlSession.getMapper(DeptMapper.class).findByDeptName("广告");
for (Emp emp :emps) {
logger.debug("编号:"+emp.getEmpno()+"\t姓名:"+emp.getEmpname());
}
sqlSession.close();
}
@Test
public void addDeptByName(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
int i = sqlSession.getMapper(DeptMapper.class).addDeptByName("XXX");
if (i>0){
sqlSession.commit();
logger.debug("添加数据成功"+i+"条");
}
sqlSession.close();
this.findAll();
}
@Test
public void addDept(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
Dept dept = new Dept();
dept.setDeptno(1);
dept.setDeptname("娱乐部");
try {
int i = sqlSession.getMapper(DeptMapper.class).addDept(dept);
if (i>0){
sqlSession.commit();
logger.debug("添加数据成功"+i+"条");
}
} catch (Exception e) {
sqlSession.rollback();
logger.debug("数据添加失败!");
e.printStackTrace();
} finally {
MybatisUtil.closeSqlSession(sqlSession);
}
this.findAll();
}
@Test
public void delDept(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
try {
int i = sqlSession.getMapper(DeptMapper.class).delDept(12);
if (i>0){
sqlSession.commit();
logger.debug("删除数据成功"+i+"条");
}
} catch (Exception e) {
sqlSession.rollback();
logger.debug("数据删除失败!");
e.printStackTrace();
} finally {
MybatisUtil.closeSqlSession(sqlSession);
}
this.findAll();
}
@Test
public void modifyDept(){
SqlSession sqlSession = MybatisUtil.createSqlSession();
try {
int i = sqlSession.getMapper(DeptMapper.class).modifyDept("测试部", "销售部");
if (i>0){
sqlSession.commit();
logger.debug("修改数据成功"+i+"条");
}
} catch (Exception e) {
sqlSession.rollback();
logger.debug("修改数据失败!!!");
e.printStackTrace();
} finally {
MybatisUtil.closeSqlSession(sqlSession);
}
}

  2.Spring框架搭建

    依赖的jar包:(maven添加以下依赖即可)

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>

    多种数据源的引用:

<!--添加数据源-->
<!--spring JDBCTemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!--dbcp 数据源-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>

    DAO层实现:(为了使用getJdbcTempalte()方法需要注入/实现JdbcDaoSupport接口)

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; public class NewsDaoImpl extends JdbcDaoSupport implements INewsDao {
@Override
public List<News> findAll() {
String sql = "SELECT * FROM infosm_news";
List<News> list = getJdbcTemplate().query(sql, new RowMapper<News>() {
@Override
public News mapRow(ResultSet rs, int rowNum) throws SQLException {
News news = new News();
news.setNewsid(rs.getInt("newsid"));
news.setNewstitle(rs.getString("newstitle"));
news.setNewscontent(rs.getString("newscontent"));
news.setClickcount(rs.getInt("clickcount"));
return news;
}
});
return list;
}
}

    核心配置文件: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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通过bean元素生命需要Spring创建的实例。该实例的类型通过class属性指定,
并通过id属性为该实例制定一个名称,以便于访问-->
<!--DataSource jdbc-->
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///infosm"/>
<property name="username" value="root"/>
<property name="password" value="tengyu"/>
</bean>
<!--DataSource druid-->
<!--<bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///infosm"/>
<property name="username" value="root"/>
<property name="password" value="tengyu"/>
</bean>-->
<!--DataSource c3p0-->
<!--<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///infosm"/>
<property name="user" value="root"/>
<property name="password" value="tengyu"/>
</bean>-->
<!--DataSource dbcp-->
<!--<bean id="dateSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///infosm"/>
<property name="username" value="root"/>
<property name="password" value="tengyu"/>
</bean>-->
<!--jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"/>
</bean>
<!--newsDao-->
<bean id="newsDao" class="cn.infosm.dao.impl.NewsDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!--newsService-->
<bean id="newsService" class="cn.infosm.service.impl.NewsServiceImpl">
<property name="dao" ref="newsDao"/>
</bean>
<!--talkDao-->
<bean id="talkDao" class="cn.infosm.dao.impl.TalkDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!--talkService-->
<bean id="talkService" class="cn.infosm.service.impl.TalkServiceImpl">
<property name="dao" ref="talkDao"/>
</bean>
</beans>

    正常测试即可:

@Test
public void findAllNews(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
INewsService newsService = (INewsService) context.getBean("newsService");
List<News> list = newsService.findAll();
for (News news :list) {
System.out.println(news.getNewstitle());
} } @Test
public void findAllTalks(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ITalkService talkService = (ITalkService) context.getBean("talkService");
List<Talk> list = talkService.findAll();
for (Talk talk :list) {
System.out.println(talk.getTid()+talk.getContent()+talk.getTalktime());
} }

Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(一:知识点回顾)的更多相关文章

  1. Spring学习笔记四 整合SSH

    三大框架架构(整合原理) 步骤1:导包 Hibernate包 1.Hibernate包,hibernate/lib/required 2.hibernate/lib/jpa | java persis ...

  2. Spring学习笔记(二) 初探Spring

    版权声明 笔记出自<Spring 开发指南>一书. Spring 初探 前面我们简单介绍了 Spring 的基本组件和功能,现在我们来看一个简单示例: Person接口Person接口定义 ...

  3. Spring学习笔记(1)——初识Spring

    一.Spring是什么       通常说的Spring其实指的是Spring Framework,它是Spring下的一个子项目,Spring围绕Spring Framework这个核心项目开发了大 ...

  4. Spring学习笔记之整合struts

    1.现有项目是通过 <action    path="/aaaaAction"                type="org.springframework.w ...

  5. Spring学习笔记之整合hibernate

    1.web.xml里边要配置好对应的springxml的路径 <context-param> <param-name>contextConfigLocation</par ...

  6. Spring 学习笔记之整合Hibernate

    Spring和Hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心SQ ...

  7. 【Spring学习笔记-1】Myeclipse下Spring环境搭建

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  8. Spring 学习笔记(一):Spring 入门

    1 Spring简介 Spring是一个轻量级Java开发框架,最早由Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题,是一个分层的Java SE/EE ful ...

  9. Spring学习笔记之四----基于Annotation的Spring AOP编程

    你能使用@Aspect annotation将某个Java类标注为Aspect,这个Aspect类里的所有公有方法都可以成为一个Advice,Spring提供了5个Annotation去将某个方法标注 ...

  10. Spring学习笔记之三----基于Annotation的Spring IOC配置

    使用Annotation 来创建Bean有两种方式 在配置类中创建bean(配置类是指标注为@Configuration的类),在配置类中每一个创建bean的方法都应该标注为@Bean,可以在@Bea ...

随机推荐

  1. [ActionScript 3.0] 使用Embed在类中嵌入字体

    package { import flash.display.Sprite; import flash.text.Font; import flash.text.TextField; import f ...

  2. c#中的classes和objects一些知识【1】

    首先我们需要知道面向对象语言(Object-oriented language)的三大特点:封装(Encapulation),继承(Inheritance),多态(Polymorphism). 引言: ...

  3. Azure Powershell获取Azure虚拟机的操作系统型号及具体版本

    Azure ARM 模式虚拟机: 1.登陆Azure账号 Add-AzureRmAccount -EnvironmentName AzurechinaCloud 2.选择指定订阅 Select-Azu ...

  4. NASA的10条代码编写原则

    NASA的10条代码编写原则 作者: Gerard J. Holzmann 来源: InfoQ 原文链接 英文原文:NASA's 10 Coding Rules for Writing Safety ...

  5. 洛谷 P3227 [HNOI2013]切糕(最小割)

    题解 Dinic求最小割 题目其实就是求最小的代价使得每个纵轴被分成两部分 最小割!!! 我们把每个点抽象成一条边,一个纵轴就是一条\(S-T\)的路径 但是题目要求\(|f(x,y)-f(x',y' ...

  6. 01背包--hdu2639

    hdu-2639 The title of this problem is familiar,isn't it?yeah,if you had took part in the "Rooki ...

  7. excel时间戳转化为标准日期(日期转化为日期戳)

    最近在学习python将数据导入到excel,发现日期变成数字而不是日期格式的问题. 第一眼看去肯定是excel单元格格式问题,一般excel单元格格式为常规,而常规处理日期时就显示为数字,所以就想到 ...

  8. 使用Maven运行测试提示Module sdk 1.5的解决方法

    解决方法: 1. 配置Project Structure 2. 在MAVEN_HOME/conf/setting.xml中添加profile 3. 在Maven项目的pom.xml文件里添加标签 三种 ...

  9. 学习python 3 入门知识

    1.安装 http://www.runoob.com/python3/python3-install.html https://www.python.org/ 2.使用 工具一:IDLE IDLE 是 ...

  10. 关于DES加密

    数据加密算法(Data Encryption Algorithm,DEA)是一种对称加密算法,很可能是使用最广泛的密钥系统,特别是在保护金融数据的安全中,最初开发的DEA是嵌入硬件中的.通常,自动取款 ...