spring
导入依赖pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.2.9.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</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-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-test</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
创建applicationContext文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.lyf">
<!--controller是由springmvc来扫描,需要将controller排除在外-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
导入log4j文件 log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
TestService
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestService {
private static final Logger log = Logger.getLogger(TestService.class.getName());
@Autowired
IPersonService iPersonService;
@Test
public void test01(){
List<Person> list=iPersonService.findAll();
log.info(list+"list");
Person person = new Person("jack",200.00);
iPersonService.save(person);
}
}
IPersonService
public interface IPersonService {
List<Person> findAll();
void save(Person person);
}
PersonServiceimpl
@Service
public class PersonServiceimpl implements IPersonService {
@Autowired
IPersonDao iPersonDao;
@Override
public List<Person> findAll() {
List<Person> list = iPersonDao.findAll();
return list;
}
@Override
public void save(Person person) {
iPersonDao.save(person);
}
}
IPersonDao
public interface IPersonDao {
List<Person> findAll();
void save(Person person);
}
PersonDaoimpl
@Repository
public class PersonDaoimpl implements IPersonDao {
@Override
public List<Person> findAll() {
System.out.println("nihao");
return null;
}
@Override
public void save(Person person) {
System.out.println( "save");
}
}
springmvc
在web.xml文件中配置前端控制器,过滤器,监听器并且添加配置文件的信息
<!--设置配置文件的路径 service dao-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--解决中文乱码的过滤器-->
<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>
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置前端控制器 controller-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--启动服务器,创建该servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springmvc.xml配置文件
开启组件扫描,配置视图解析器,配置静态资源
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--springmvc是web层 UserController @Controller -->
<!-- 打开组件扫描-->
<context:component-scan base-package="com.lyf">
<!-- 只处理带@Controller的请求-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置的视图解析器对象 /WEB-INF/pages/success.jsp -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--过滤静态资源 .js .css png-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!--开启SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody-->
<mvc:annotation-driven/>
</beans>
测试Personcontroller
@Controller
public class Personcontroller {
@RequestMapping("list")
public String test01(Model model){
ArrayList<Person> list = new ArrayList<>();
Person person = new Person("小明",1000.00);
Person person1 = new Person("小红",1000.00);
Person person2 = new Person("小白",1000.00);
list.add(person);
list.add(person1);
list.add(person2);
model.addAttribute("list",list);
return "list";
}
}
list.jsp
<table border="1px" width="100%">
<c:forEach items="${list}" var="preson">
<tr>
<td>${preson.name}</td>
<td>${preson.money}</td>
</tr>
</c:forEach>
</table>
mybatis
四大基本信息
<?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">
<!--dtd是对xml配置标签与属性的约束-->
<configuration>
<settings>
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<package name="com.lyf.domain"/>
</typeAliases>
<!-- environments环境 开发环境,生产环境-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc的事务管理 -->
<transactionManager type="JDBC"/>
<!-- dataSource Mybatis自带数据源连接池-->
<dataSource type="POOLED">
<!-- 四大信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 配置多个映射文件-->
<mappers>
<mapper resource="com\lyf\dao\IPersonDao.xml"></mapper>
<!-- <package name="com.lyf.dao"/>-->
</mappers>
</configuration>
pom.xml文件依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
IPersonDao.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">
<mapper namespace="com.lyf.dao.IPersonDao">
<select id="findAll" resultType="person">
select * from person where id=#{id}
</select>
</mapper>
TestMybatis
public class TestMybatis {
private SqlSession sqlSession;
@Autowired
IPersonDao personDao;
@Before
public void init(){
//加载配置文件
InputStream resourceAsStream = TestMybatis.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
//由SqlSessionFactoryBuilder创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession= sqlSessionFactory.openSession();
}
@After
public void destory(){
sqlSession.commit();
sqlSession.close();
}
@Test
public void test01(){
IPersonDao mapper = sqlSession.getMapper(IPersonDao.class);
List<Person> list1 = mapper.findAll(1);
System.out.println(list1);
}
}
spring与mybatis的整合
(1)Spring整合MyBatis需要添加整合包
(2)什么是mybatis-spring
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中
不需要调用 session.getMapper(IpersonDao.class)
session.commit()
session.close()
pom.xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
applicationContext.xml配置
<!--数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- com.wzx.domain.Person person-->
<property name="typeAliasesPackage" value="com.lyf.domain"/>
</bean>
<!--xml-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lyf.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
TetsDasource
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TetsDasource {
@Autowired
IPersonDao iPersonDao;
@Test
public void test01(){
List<Person> list = iPersonDao.findAll();
System.out.println(list);
}
}
事物管理配置
<!--事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事物的隔离级别-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:pointcut id="service" expression="execution(* com.lyf.service.impl.*Serviceimpl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="service"></aop:advisor>
</aop:config>
测试
@Test
public void test02() {
List<Person> personList = new ArrayList<>();
personList.add(new Person("jac2k", 100.00));
personList.add(new Person("ros2e", 200.00));
personList.add(new Person("ton2y", 300.00));
iPersonService.savePersons(personList);
}
savePersons
public void savePersons(List<Person> personList) {
for (int i=0;i<personList.size();i++){
iPersonDao.save(personList.get(i));
}
}