spring整合mybatis

第一步、构建spring mybatis依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>

<!--spring-mybatis包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>

<!-- mysql 驱动jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.7.20</version>
</dependency>
<!--引入ddcp 用来配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>


<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
</dependencies>

第二步、构建bean
package com.li.familytree.core.bean;

import java.util.ArrayList;
import java.util.List;

/**
* <pre>
* Created by IntelliJ IDEA.
* User: 1100085
* Date: 2018/3/27
* Time: 14:55
* To change this template use File | Settings | File Templates.
*
* @author limy
* </pre>
*/
public class StudentBean {
//学生号
private String code;

//学生性别
private String sex;
//学生姓名
private String name;
  //学生年龄
private int age;
  //学生所在班
private String classgrade;

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getClassgrade() {
return classgrade;
}

public void setClassgrade(String classgrade) {
this.classgrade = classgrade;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

/*    public List<StudentBean> getSudentBean(StudentBean studentBean){

List arrayList = new ArrayList<StudentBean>();

arrayList.add(studentBean.getAge());
arrayList.add(studentBean.getClassgrade());
arrayList.add(studentBean.getCode());
arrayList.add(studentBean.getName());
arrayList.add(studentBean.getSex());
return arrayList;
}*/

}

第三步 创建DAO层

package com.li.familytree.core.dao;

import com.li.familytree.core.bean.StudentBean;

import java.util.List;

/**
* <pre>
* Created by IntelliJ IDEA.
* User: 1100085
* Date: 2018/3/27
* Time: 15:30
* To change this template use File | Settings | File Templates.
*
* @author limy
* </pre>
*/
public interface StudentMsgDao {

public int insertStudentMsg(StudentBean studentBean);

public List<StudentBean> getStudent(String code);

public int updateStudent(String code);

public int delete(String code);
}

第四步 创建服务层
package com.li.familytree.core.service;

import com.li.familytree.core.bean.StudentBean;
import com.li.familytree.core.dao.StudentMsgDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
* <pre>
* Created by IntelliJ IDEA.
* User: 1100085
* Date: 2018/3/27
* Time: 15:54
* To change this template use File | Settings | File Templates.
*
* @author limy
* </pre>
*/

@Service("studentService")
public class StudentService {

@Resource
private StudentMsgDao studentMsgDao;

public int insertStudentMsg(StudentBean studentBean){

return studentMsgDao.insertStudentMsg(studentBean);
}

public List<StudentBean> getStudent(String code){
return studentMsgDao.getStudent(code);
}

public int delete(String code){

return studentMsgDao.delete(code);
}

public int updateSudent(String code){
return studentMsgDao.updateStudent(code);
}


}
第五步 整合spring和mybatis

jdbc.propertis 内容
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://10.17.21.001:3306/private?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

initialSize=5
maxActive=20
maxIdle=20
minIdle=1
maxWait=3000

spring-mybatis 整合
<?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:context="http://www.springframework.org/schema/context"
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.xsd">

<!-- 自动扫描 -->
<context:component-scan base-package="com.li.familytree.core" />

<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="validationQuery">
<value>SELECT 1</value>
</property>
<property name="testOnBorrow">
<value>true</value>
</property>

<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.li.familytree.core.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>

mapper 层 配置
<?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="com.li.familytree.core.dao.StudentDao" >
<resultMap id="StudentResultMap" type="com.li.familytree.core.bean.StudentBean" >
<result column="code" property="code" />
<result column="name" property="name" />
<result column="sex" property="sex" />
<result column="age" property="age" />
<result column="classgrade" property="classgrade"/>
</resultMap>

<insert id="insertStudentMsg" parameterType="com.li.familytree.core.bean.StudentBean" >
insert into studentmsg(
code,
name,
sex,
age,
classgrade
) values (
#{code},
#{name},
#{sex},
#{age},
#{classgrade}
)
</insert>
<update id="updateStudent" parameterType="com.li.familytree.core.bean.StudentBean" >
update studentmsg
<set >
<if test="name != null" >
name = #{name},
</if>
<if test="sex != null" >
sex = #{sex},
</if>
<if test="age != null" >
age = #{age},
</if>
<if test="classgrade != null" >
classgrade = #{classgrade},
</if>
</set>
where code = #{code}
</update>

<select id="getStudent" parameterType="map" resultMap="StudentResultMap">
select * FROM studentmsg WHERE code = #{code}
</select>

</mapper>


第六步:直接跑
package com.li.familytree.core.persisdata;

import com.li.familytree.core.bean.StudentBean;
import com.li.familytree.core.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;


/**
* <pre>
* Created by IntelliJ IDEA.
* User: 1100085
* Date: 2018/3/27
* Time: 17:05
* To change this template use File | Settings | File Templates.
*
* @author limy
* </pre>
*/
public class ToPersistMsg {

protected static Logger LOGGER = LoggerFactory.getLogger(ToPersistMsg.class);

private StudentBean studentBean;

private StudentService studentService;

private List<StudentBean> arrayList = new ArrayList<StudentBean>(5);

public void perist(){

List<StudentBean> student = studentService.getStudent("2013003451");
for (StudentBean o:student){
System.out.println(o.getAge());
}
studentService.insertStudentMsg(studentBean);
LOGGER.info("向MySQL存储数据完成");
}

public void setStudentBean(StudentBean studentBean) {
this.studentBean = studentBean;
}

public void setSudentService(StudentService sudentService) {
this.studentService = sudentService;
}

public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("appApplication.xml");
ToPersistMsg toPersistMsg1 = (ToPersistMsg) classPathXmlApplicationContext.getBean("toPersistMsg");
toPersistMsg1.perist();
}

}

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d22bbb7: startup date [Wed Mar 28 14:28:15 CST 2018]; root of context hierarchy
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [appApplication.xml]
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [student.xml]
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [spring-mybatis.xml]
[org.springframework.beans.factory.support.DefaultListableBeanFactory] - Overriding bean definition for bean 'studentService': replacing [Generic bean: class [com.li.familytree.core.service.StudentService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\qiakefirm\streaming-etl\streamingdata-core\target\classes\com\li\familytree\core\service\StudentService.class]] with [Generic bean: class [com.li.familytree.core.service.StudentService]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [student.xml]]
[org.mybatis.spring.mapper.ClassPathMapperScanner] - Skipping MapperFactoryBean with name 'studentDao' and 'com.li.familytree.core.dao.StudentDao' mapperInterface. Bean already defined with the same name!
[org.mybatis.spring.mapper.ClassPathMapperScanner] - No MyBatis mapper was found in '[com.li.familytree.core.dao]' package. Please check your configuration.
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [student.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [jdbc.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [student.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [jdbc.properties]
[org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanIsAbstractException: Error creating bean with name 'studentDao': Bean definition is abstract
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.li.familytree.core.persisdata.ToPersistMsg.main(ToPersistMsg.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanIsAbstractException: Error creating bean with name 'studentDao': Bean definition is abstract
at org.springframework.beans.factory.support.AbstractBeanFactory.checkMergedBeanDefinition(AbstractBeanFactory.java:1273)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:445)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:419)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:544)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:304)
... 18 more

Process finished with exit code 1

通过分析发现,我们发现这是有studentDao 好像在spring-mybatis出现重名了,具体原因我为看过spring-mybatis暂不清楚,不过我是这样解决;修改Dao借口的类名

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d22bbb7: startup date [Wed Mar 28 14:31:34 CST 2018]; root of context hierarchy
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [appApplication.xml]
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [student.xml]
[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [spring-mybatis.xml]
[org.springframework.beans.factory.support.DefaultListableBeanFactory] - Overriding bean definition for bean 'studentService': replacing [Generic bean: class [com.li.familytree.core.service.StudentService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\qiakefirm\streaming-etl\streamingdata-core\target\classes\com\li\familytree\core\service\StudentService.class]] with [Generic bean: class [com.li.familytree.core.service.StudentService]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [student.xml]]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [student.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [jdbc.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [student.properties]
[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [jdbc.properties]
[org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
10

Process finished with exit code

然后就成功,也没报错,数据也插入到mysql里面





posted @ 2018-03-28 14:35  王鑫宇者  阅读(353)  评论(0编辑  收藏  举报