Spring+Mybatis整合练习
比较麻烦的就是pom.xml的maven配置,有好多的包要写上来
重点就是applicationContext.xml这个Spring的配置文件,这回把Mybatis的SqlSession也交给他了
总之我注释写的很详细,以后哪一天忘了回来看应该还是看得懂的
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>ssmdemo1</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssmdemo1 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>ssmdemo1</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>
Spring主配置文件
这里有个读取器,我写了个名字叫做mysql.properties的配置文件,主要就是用于连接数据库的几个参数在配置文件里定义了,就放这把
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/test0605?serverTimezone=Asia/Shanghai username=root password=614
applicationContext
<?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: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"> <!--定义读取属性文件的读取器--> <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 SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="mapper/*.xml"/> </bean> <!--事务管理器--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--声明式事务--> <tx:advice transaction-manager="transactionManager" id="advisor1"> <tx:attributes> <!--方法名正则匹配 propagation传播行为:事务处理方式 REQUIRED:切入点方法执行时,如果未开启事务,则开启新事务;若已开启事务,则加入到已开始的事务--> <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"/> <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"/> <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"/> <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true"/> </tx:attributes> </tx:advice> <!--配置事务AOP--> <aop:config> <aop:pointcut id="p1" expression="execution(* top.yibobo.service.*.*(..))"/> <aop:advisor advice-ref="advisor1" pointcut-ref="p1"/> </aop:config> <!--定义Mapper实例--> <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="AuthorMapper"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" value="top.yibobo.dao.AuthorMapper"/> </bean> <!--定义service实例--> <bean id="authorService" class="top.yibobo.service.AuthorMapperImpl"> <property name="dao" ref="AuthorMapper"/> </bean> <!--定义Mapper实例--> <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="ArticleMapper"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" value="top.yibobo.dao.ArticleMapper"/> </bean> <!--定义service实例--> <bean id="articleService" class="top.yibobo.service.ArticleMapperImpl"> <property name="dao" ref="ArticleMapper"/> </bean> <!--定义Mapper实例--> <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="ArticleCommtMapper"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" value="top.yibobo.dao.ArticleCommtMapper"/> </bean> <!--定义service实例--> <bean id="articleCommtService" class="top.yibobo.service.ArticleCommtMapperImpl"> <property name="dao" ref="ArticleCommtMapper"/> </bean> </beans>
Mybatis的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"> <!--ArticleCommtMapper接口的映射文件--> <mapper namespace="top.yibobo.dao.ArticleCommtMapper"> <resultMap id="articlecommtlist1" type="top.yibobo.pojo.ArticleCommt"> <id property="id" column="id"/> <result property="commt" column="commt"/> <result property="commtTime" column="commt_time"/> <!--<association property="author" column="au_id" javaType="Author" select="top.yibobo.dao.AuthorDao.findById"> </association>--> <!--<association property="article" column="ar_id" javaType="Article" select="top.yibobo.dao.ArticleMapper.findById"> </association>--> </resultMap> <select id="findAll" resultMap="articlecommtlist1"> SELECT * FROM article_commt </select> <select id="findById" resultMap="articlecommtlist1"> SELECT * FROM article_commt WHERE au_id=#{id} </select> <!--<select id="findById"/>--> </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="articlelist1" 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" resultMap="top.yibobo.dao.AuthorMapper.authorlist1"> </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> <sql id="where"> <where> <if test="name!=null"> name=#{name} </if> <if test="title!=null"> AND tiele LIKE #{title} </if> <if test="ftime!=null and etime!=null"> AND birthday BETWEEN #{ftime} AND #{etime} </if> </where> </sql> <select id="findPage" resultMap="articlelist1"> <include refid="find"/> <include refid="where"/> <if test="orderby!=null"> ORDER BY #{orderby} <choose> <when test="type!=null"> #{type} </when> <otherwise> ASC </otherwise> </choose> </if> <bind name="pageNo" value="(page-1)*pageSize"/> LIMIT #{pageNo},#{pageSize} </select> <select id="findAll" resultMap="articlelist1"> <include refid="find"/> </select> <select id="findById" resultMap="articlelist1"> <include refid="find"/> WHERE au.id=#{id} </select> </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"> <!--AuthorDao接口的映射文件--> <mapper namespace="top.yibobo.dao.AuthorMapper"> <resultMap id="authorlist1" type="top.yibobo.pojo.Author"> <id property="id" column="auid"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="birthday" column="birthday"/> <result property="address" column="address"/> <result property="phone" column="phone"/> </resultMap> <select id="findById" resultMap="authorlist1"> SELECT id auid,name,sex,birthday,address,phone FROM Author WHERE id=#{id} </select> <resultMap id="authorlist2" type="top.yibobo.pojo.Author"> <id property="id" column="auid"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="birthday" column="birthday"/> <result property="address" column="address"/> <result property="phone" column="phone"/> <collection property="articles" column="auid" select="top.yibobo.dao.ArticleMapper.findById" ofType="top.yibobo.pojo.Article"> </collection> <collection property="articleCommts" column="auid" select="top.yibobo.dao.ArticleCommtMapper.findById" ofType="top.yibobo.pojo.ArticleCommts"> </collection> </resultMap> <select id="findAll" resultMap="authorlist2"> SELECT id auid,name,sex,birthday,address,phone FROM Author </select> </mapper>
java各个包和接口和实现类们
dao层
package top.yibobo.dao; import top.yibobo.pojo.ArticleCommt; import java.util.List; public interface ArticleCommtMapper { List<ArticleCommt> findAll(); }
package top.yibobo.dao; import org.apache.ibatis.annotations.Param; import top.yibobo.pojo.Article; import java.util.List; import java.util.Map; public interface ArticleMapper { List<Article> findAll(); List<Article> findPage(Map<String, Object> map); Article findById(@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.sql.Date; public class Article { 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.sql.Date; import java.util.List; public class Author { private int id; private String name; private String sex; private Date birthday; private String address; private String phone; private List<Article> articles; private List<ArticleCommt> articleCommts; public Author() { } public List<Article> getArticles() { return articles; } public void setArticles(List<Article> articles) { this.articles = articles; } public List<ArticleCommt> getArticleCommts() { return articleCommts; } public void setArticleCommts(List<ArticleCommt> articleCommts) { this.articleCommts = articleCommts; } 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 + '\'' + ", articles=" + articles + ", articleCommts=" + articleCommts + '}'; } }
package top.yibobo.pojo; import java.sql.Date; public class ArticleCommt { private Integer id; private String commt; private Date commtTime; private Author author; private Article article; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCommt() { return commt; } public void setCommt(String commt) { this.commt = commt; } public Date getCommtTime() { return commtTime; } public void setCommtTime(Date commtTime) { this.commtTime = commtTime; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } @Override public String toString() { return "ArticleCommt{" + "id=" + id + ", commt='" + commt + '\'' + ", commtTime=" + commtTime + ", author=" + author + ", article=" + article + '}'; } }
service层
package top.yibobo.service; import top.yibobo.dao.ArticleCommtMapper; import top.yibobo.pojo.ArticleCommt; import java.util.List; public class ArticleCommtMapperImpl implements ArticleCommtMapper { private ArticleCommtMapper dao; public void setDao(ArticleCommtMapper dao) { this.dao = dao; } @Override public List<ArticleCommt> findAll() { return dao.findAll(); } }
package top.yibobo.service; import top.yibobo.dao.ArticleMapper; import top.yibobo.pojo.Article; import java.util.List; import java.util.Map; public class ArticleMapperImpl implements ArticleMapper { private ArticleMapper dao; public void setDao(ArticleMapper dao) { this.dao = dao; } @Override public List<Article> findAll() { return dao.findAll(); } @Override public List<Article> findPage(Map<String, Object> map) { return dao.findPage(map); } @Override public Article findById(int id) { return dao.findById(id); } }
package top.yibobo.service; import top.yibobo.dao.AuthorMapper; import top.yibobo.pojo.Author; import java.util.List; public class AuthorMapperImpl implements AuthorMapper{ private AuthorMapper dao; public void setDao(AuthorMapper dao) { this.dao = dao; } @Override public int addAuthor(Author author) { return dao.addAuthor(author); } @Override public int updateAuthor(Author author) { return dao.updateAuthor(author); } @Override public int deleteAuthor(int id) { return dao.deleteAuthor(id); } @Override public List<Author> findById(int id) { return dao.findById(id); } @Override public List<Author> findAll() { return dao.findAll(); } }
最终测试类
package top.yibobo.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import top.yibobo.dao.ArticleCommtMapper; import top.yibobo.dao.ArticleMapper; import top.yibobo.dao.AuthorMapper; import top.yibobo.pojo.Article; import top.yibobo.pojo.ArticleCommt; import top.yibobo.pojo.Author; import java.util.List; public class AuthorTest { @Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); AuthorMapper authorService = ctx.getBean("authorService", AuthorMapper.class); List<Author> all = authorService.findAll(); all.forEach(author -> System.out.println(author)); } @Test public void test2(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ArticleMapper articleService = ctx.getBean("articleService", ArticleMapper.class); List<Article> all = articleService.findAll(); all.forEach(article -> System.out.println(article)); } @Test public void test3(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ArticleCommtMapper articleCommtService = ctx.getBean("articleCommtService", ArticleCommtMapper.class); List<ArticleCommt> all = articleCommtService.findAll(); all.forEach(articleCommt -> System.out.println(articleCommt)); } }