Spring+Mybatis的注解配置整合
跟之前的普通的XML配置有了许多的不同
总体来说我觉得注解配置简单一些
maven项目的pom.xml是真的又臭又长,就放到最后把
先把applicationContext.xml放上来
mysql的配置和log4j的配置
log4j.rootCategory=ERROR,stdout log4j.logger.org.springframework=ERROR log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
#mysql连接配置 driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/test0605?serverTimezone=Asia/Shanghai username=root password=614
<?xml version="1.0" encoding="UTF-8"?> <!--Spring bean容器配置文件--> <beans xmlns="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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!--组件扫描基础包--> <context:component-scan base-package="top.yibobo.dao,top.yibobo.service"/> <!--应用注解配置--> <context:annotation-config /> <!--定义读取属性文件的读取器--> <util:properties id="reader" location="classpath:mysql.properties"/> <!--创建c3p0连接池数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="#{reader[driver]}"/> <property name="jdbcUrl" value="#{reader[url]}"/> <property name="user" value="#{reader[username]}"/> <property name="password" value="#{reader[password]}"/> <property name="maxPoolSize" value="10"/> <property name="maxIdleTime" value="120"/> </bean> <!--指定MyBatis映射接口扫描的基础包--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="top.yibobo.dao"/> </bean> <!--mybatis SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!--事务管理器--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--事务使用注解驱动--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
mybatis的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"> <!--ArticleMapper接口的映射文件--> <mapper namespace="top.yibobo.dao.ArticleMapper"> <resultMap id="arList" type="top.yibobo.pojo.Article"> <id property = "id" column = "arid"/> <result property = "title" column = "title"/> <result property = "content" column = "content"/> <result property = "publishTime" column = "publish_time"/> <association property="author" javaType="top.yibobo.pojo.Author"> <id property="id" column="auid" /> <result property="name" column="name"/> </association> </resultMap> <sql id="find"> SELECT au.id auid,name,sex,birthday,address,phone, ar.id arid,title,content,publish_time,au_id FROM article ar LEFT JOIN author au ON ar.au_id=au.id </sql> <select id="findAll" resultMap="arList"> <include refid="find"/> </select> </mapper>
dao层
package top.yibobo.dao; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import top.yibobo.pojo.Article; import java.util.List; @Repository public interface ArticleMapper { List<Article> findAll(); @Select("select * from article where id=#{id}") Article findById(@Param("id") int id); @Insert("insert into article values(null,#{title},#{content},#{publishTime},#{author.auid})") int addArticle (Article article); @Update("update article set title=#{title} where id=#{id}") int updateArticle(Article article); @Delete("delete from article where id=#{id}") int deleteArticle(@Param("id") int id); }
package top.yibobo.dao; import org.apache.ibatis.annotations.Param; import top.yibobo.pojo.Author; import java.util.List; public interface AuthorMapper { int addAuthor(Author author); int updateAuthor(Author author); int deleteAuthor(int id); List<Author> findById(@Param("id") int id); List<Author> findAll(); }
pojo层
package top.yibobo.pojo; import java.io.Serializable; import java.sql.Date; public class Article implements Serializable{ private Integer id; private String title; private String content; private Date publishTime; private Author author; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getPublishTime() { return publishTime; } public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public String toString() { return "Article{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", publishTime=" + publishTime + ", author=" + author + '}'; } }
package top.yibobo.pojo; import java.io.Serializable; import java.sql.Date; public class Author implements Serializable{ private int id; private String name; private String sex; private Date birthday; private String address; private String phone; public Author() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Author{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", address='" + address + '\'' + ", phone='" + phone + '\'' + '}'; } }
service层
package top.yibobo.service; import org.apache.ibatis.annotations.*; import top.yibobo.pojo.Article; import java.util.List; public interface ArticleService { List<Article> findAll(); Article findById(@Param("id") int id); int addArticle (Article article); int updateArticle(Article article); int deleteArticle(@Param("id") int id); }
最关键的 service实现
package top.yibobo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import top.yibobo.dao.ArticleMapper; import top.yibobo.pojo.Article; import java.util.List; @Service("articleService") @Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly = true)//不开启事务,只读 public class ArticleServiceImpl implements ArticleService { @Autowired//组件注解,自动绑定。把bean容器中叫articleMapper的自动绑定上来 //@Resource(name = "articleMapper") private ArticleMapper articleMapper; @Override public List<Article> findAll() { return articleMapper.findAll(); } @Override public Article findById(int id) { return articleMapper.findById(id); } @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT,rollbackFor = Exception.class) @Override public int addArticle(Article article) { return articleMapper.addArticle(article); } @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT,rollbackFor = Exception.class) @Override public int updateArticle(Article article) { return articleMapper.updateArticle(article); } @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT,rollbackFor = Exception.class) @Override public int deleteArticle(int id) { return articleMapper.deleteArticle(id); } }
测试类
package top.yibobo.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import top.yibobo.pojo.Article; import top.yibobo.service.ArticleService; import java.util.List; public class ArticleTest { @Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ArticleService articleService = ctx.getBean("articleService", ArticleService.class); List<Article> all = articleService.findAll(); all.forEach(article -> System.out.println(article)); } }
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>top.yibobo.demos</groupId> <artifactId>ssmdemo2</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssmdemo2 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <spring.version>5.0.4.RELEASE</spring.version> <slf4j.version>1.7.5</slf4j.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--导入mysql驱动类包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.11</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- apache commons begin --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>commons-digester</groupId> <artifactId>commons-digester</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>commons-chain</groupId> <artifactId>commons-chain</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- java --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>se.jiderhamn.classloader-leak-prevention</groupId> <artifactId>classloader-leak-prevention-servlet</artifactId> <version>2.1.0</version> </dependency> </dependencies> <build> <finalName>ssmdemo2</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>