赞
踩
MyBatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
Spring是一个开源的重量级的应用开发框架,其目的是用于简化企业级应用程序开发,降低开发者的开发难度
Spring提供的IOC和AOP应用,可以将组建的耦合度降到最低(即解耦),便于系统日后的维护和升级
Spring为系统提供了一个整体的解决方案,开发者可以利用它自身提供的功能外,也可以与第三方框架和技术整合应用,可以自由选择利用哪种技术进行开发
SpringMVC是Spring框架的一个模块,Spring和SpringMVC无需中间层整合
SpringMVC提供了基于MVC(模型—视图—控制器)架构和用于开发灵活和松耦合的web应用程序的组件
点击File,新建Project项目
选中Maven,勾上Creater from archetype选项,按照图中数字顺序选中后点击Next按钮即可
项目创建完成之后在main包在将没有的java,resources,test包自己创建即可
我们可以看到包创建好之后是灰色的,需要选中相应的文件夹右击Mark Directory as,选中相应的颜色即可
在pom.xml文件中导入所需要的的jar包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> <!--Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.24</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.24</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.24</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.24</version> </dependency> <!--Aop--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.23</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.7</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.2</version> <scope>runtime</scope> </dependency>
实体类(com.cn.pojo)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
持久层接口(com.cn.mapper)
public interface UserMapper {
//查询所有用户
public List<User> findAll();
}
业务层接口及实现类(com.cn.service)
public interface UserService {
//查询所有用户
public List<User> findAll();
}
public class UserServiceImpl implements UserService {
/**
* 目前还没有整合MyBatis,先模拟代码实现
* @return
*/
@Override
public List<User> findAll() {
System.out.println("UserServiceImpl::findAll()");
return null;
}
}
Resources包下新建 spring 配置文件(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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置指定包扫描 -->
<context:component-scan base-package="com.cn"></context:component-scan>
</beans>
使用注解(@Service)配置业务层
@Service("UserServiceImpl")
public class UserServiceImpl implements UserService {
/**
* 目前还没有整合MyBatis,先模拟代码实现
* @return
*/
@Override
public List<User> findAll() {
System.out.println("UserServiceImpl::findAll()");
return null;
}
}
Test包创建测试方法
public class TestSpring {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.findAll();
}
}
在pom.xml文件中导入所需要的的jar包
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
web.xml中配置SpringMVC的核心控制器()
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 注册springmvc框架核心控制器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--配置dispatcher-servlet.xml作为mvc的配置文件--> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 解决POST提交中文乱码问题 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <!-- 设置编码格式 --> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Resources包下新建SpringMVC的配置文件(dispatcher-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--此文件负责整个mvc中的配置--> <!-- 1.配置前端控制器放行静态资源(html/css/js等,否则静态资源将无法访问) --> <mvc:default-servlet-handler/> <!-- 2.配置注解驱动,用于识别注解(比如@Controller) --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 3.配置需要扫描的包:spring自动去扫描 base-package 下的类, 如果扫描到的类上有 @Controller、@Service、@Component等注解, 将会自动将类注册为bean --> <context:component-scan base-package="com.cn"></context:component-scan> <!-- 4.配置内部资源视图解析器 prefix:配置路径前缀 suffix:配置文件后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
编写Controller(com.cn.controller)
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("UserController::findAll()");
return "list";
}
}
/WEB-INF/views/下新建list.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试SpringMVC</title>
</head>
<body>
<h1>SpringMVC,查询所有用户列表</h1>
</body>
</html>
部署Tomcat及相关环境
web.xml配置监听器启动服务创建容器
<!--配置Spring提供的监听器,用于启动服务器时加载容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
编辑UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServiceImpl userService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("UserController::findAll()");
List<User> list = userService.findAll();
return "list";
}
}
再次测试访问http://localhost:8080/user/findAll
在pom.xml文件中导入所需要的的jar包
<!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency>
Resources包下新建db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/xx_mybatis?useSSL=TRUE&userUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
db.username=root
db.password=111111
Resources包下新建MyBatis的核心信息(mybatis-config.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> <!-- 1.加载jdbc.properties文件的位置 --> <properties resource="db.properties"></properties> <!-- 2.配置开发环境,标签内可以配置多个环境,比如develop,test等 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </dataSource> </environment> </environments> <!-- 3.加载Mapper配置文件,路径以斜杠间隔: xx/xx/../xx.xml --> <mappers> <mapper class="com.cn.dao.UserMapper"/> </mappers> </configuration>
编辑userMapper,添加sql语句
public interface UserMapper {
//查询所有用户
@Select("select * from user")
public List<User> findAll();
}
Test包创建测试方法
public class TsetMyBatis { public static void main(String[] args) { SqlSession sqlSession = null; try { Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader); sqlSession = factory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> list = mapper.findAll(); for (User user : list) { System.out.println(user); } } catch (IOException e) { e.printStackTrace(); } finally { sqlSession.close(); } } }
现在我们要做SSM框架整合,可以将MyBatis的配置交给Spring去处理,把mybatis-config.xml配置文件中的内容配置到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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- <!– 配置指定包扫描 –>--> <!-- <context:component-scan base-package="com.cn"></context:component-scan>--> <!-- 1.加载jdbc.properties文件的位置 --> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!--2.配置数据库连接 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> <!-- 3.整合spring和mybatis框架 将SqlSession等对象的创建交给Spring容器 id值(sqlSessionFactory)是固定值 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 3.2.配置连接池(数据源) ref指向连接池bean对象的id值 --> <property name="dataSource" ref="dataSource"></property> </bean> <!--4.Mapper扫描,自动引入mapper类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描所有XxxMapper接口,将接口实例的创建交给spring容器 --> <property name="basePackage" value="com.cn"/> </bean> </beans>
mybatis-config.xml配置文件就可以删除了
编辑UserMapper
@Repository
public interface UserMapper {
//查询所有用户
@Select("select * from user")
public List<User> findAll();
}
编辑UserServiceImpl
@Service("UserServiceImpl")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/**
* @return
*/
@Override
public List<User> findAll() {
System.out.println("UserServiceImpl::findAll()");
return userMapper.findAll();
}
}
编辑UserController
@Controller @RequestMapping("/user") public class UserController { @Autowired private UserServiceImpl userService; @RequestMapping("/findAll") public String findAll(){ System.out.println("UserController::findAll()"); List<User> list = userService.findAll(); for (User user : list) { System.out.println(user); } return "list"; } }
重启Tomcat,测试访问
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。