Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(一:知识点回顾)
一、知识点回顾
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)(一:知识点回顾)的更多相关文章
- Spring学习笔记四 整合SSH
三大框架架构(整合原理) 步骤1:导包 Hibernate包 1.Hibernate包,hibernate/lib/required 2.hibernate/lib/jpa | java persis ...
- Spring学习笔记(二) 初探Spring
版权声明 笔记出自<Spring 开发指南>一书. Spring 初探 前面我们简单介绍了 Spring 的基本组件和功能,现在我们来看一个简单示例: Person接口Person接口定义 ...
- Spring学习笔记(1)——初识Spring
一.Spring是什么 通常说的Spring其实指的是Spring Framework,它是Spring下的一个子项目,Spring围绕Spring Framework这个核心项目开发了大 ...
- Spring学习笔记之整合struts
1.现有项目是通过 <action path="/aaaaAction" type="org.springframework.w ...
- Spring学习笔记之整合hibernate
1.web.xml里边要配置好对应的springxml的路径 <context-param> <param-name>contextConfigLocation</par ...
- Spring 学习笔记之整合Hibernate
Spring和Hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心SQ ...
- 【Spring学习笔记-1】Myeclipse下Spring环境搭建
*.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...
- Spring 学习笔记(一):Spring 入门
1 Spring简介 Spring是一个轻量级Java开发框架,最早由Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题,是一个分层的Java SE/EE ful ...
- Spring学习笔记之四----基于Annotation的Spring AOP编程
你能使用@Aspect annotation将某个Java类标注为Aspect,这个Aspect类里的所有公有方法都可以成为一个Advice,Spring提供了5个Annotation去将某个方法标注 ...
- Spring学习笔记之三----基于Annotation的Spring IOC配置
使用Annotation 来创建Bean有两种方式 在配置类中创建bean(配置类是指标注为@Configuration的类),在配置类中每一个创建bean的方法都应该标注为@Bean,可以在@Bea ...
随机推荐
- jquery鼠标经过水平180度翻转效果
Html代码: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/htm ...
- CF1106F Lunar New Year and a Recursive Sequence(矩阵快速幂+bsgs+exgcd)
题面 传送门 前置芝士 \(BSGS\) 什么?你不会\(BSGS\)?百度啊 原根 对于素数\(p\)和自然数\(a\),如果满足\(a^x\equiv 1\pmod{p}\)的最小的\(x\)为\ ...
- [ActionScript 3.0] 自定义右键菜单
将自定义右键菜单的一些属性和方法归纳到AddRightMenu.as,通过实例化此类,调用相关方法即可测试! package { import flash.display.Sprite; import ...
- TensorFlow支持GPU配置问题
目录 Tensorflow-GPU 环境条件 现有硬件 现有软件 硬件要求 软件要求 步骤 0.Visual studio 1.下载安装显卡驱动 2.下载对应版本 CUDA 3.安装配置 cuDNN ...
- iOS核心动画之视觉效果
圆角 cornerRadius确定圆角的大小 masksToBounds确定要不要裁减圆角以外的界面 图层边框 borderWidth 边框的粗细,point是衡量值. borderColor 边框的 ...
- 2016级算法第二次上机-C.AlvinZH的儿时梦想——坦克篇
872 AlvinZH的儿时梦想----坦克篇 思路 简单题.仔细看题,题目意在找到直线穿过的矩形数最小,不能从两边穿过.那么我们只要知道每一行矩形之间的空隙位置就可以了. 如果这里用二维数组记住每一 ...
- C#中简单操作Mysql数据库
以C#访问MySQL数据库,执行简单的CRUD. MySql.Data.dll是C#操作MySQL的驱动文件,是C#连接MySQL必要插件,使C#语言更简洁的操作MySQL数据库.可以用NuGet命令 ...
- vue-cli 3.5 解决 typescript cannot find file 问题。
版本: "ts-loader": "^3.5.0","typescript": "^3.3.4000", "v ...
- 高阶篇:4.2.1)DFMEA框架搭建,填写项目与要求
本章目的:明确DFMEA的数量及目标,搭建框架,填写项目与要求. 1.步骤: 1)明确DFMEA的数量及目标: 2)搭建框架(所有DFMEA的): 3)填写项目与要求: 2.1明确DFMEA的数量及目 ...
- C#集合之队列
队列是其元素按照先进先出(FIFO)的方式来处理的集合. 队列使用System.Collections.Generic名称空间中的泛型类Queue<T>实现.在内部,Queue<T& ...