Spring整合MyBatis 你get了吗?
Spring整合MyBatis
1.整体架构
dao,entity,service,servlet,xml
2..引入依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <!--cglib--> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!--mysql驱动 jar包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <!--spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.0.RELEASE</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> <!--druid 数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <!--mybatis jar包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <!--Mybatis+Spring整合--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.1</version> </dependency> <!-- Spring整合JavaWeb的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!--javaee jar--> <dependency> <groupId>javaee</groupId> <artifactId>javaee-api</artifactId> <version>5</version> </dependency> </dependencies>
3.MyBatis配置文件
配置个typeAliases 配置entity,是的访问entity包下的类可以不使用全路径。小配置中
4.xml
1.编写数据源
2.创建 SqlSessionFactoryBean 节点
2.1连接数据源
2.2写入MyBatis的配置文件(加一个classPath:)
3.创建MapperScannerConfguln 节点
3.1配置basePackage ref是dao文件夹全路径
4.配置service节点
4.1传入dao层接口(注意命名规范,接口要用I开头,方便识别)
5.编写web.xml
5.1编写上下文
5.2编写监听器
5.3编写servlet web.xml的方式
6.编写servlet
6.1编写添加图书的逻辑代码。
xml:
web.xml:
mybatis配置文件:
servlet(编写servlet记得引javaee的依赖):
页面: