其实他们的整合就相当于,将mybatis的xml配置文件,加载到spring容器中去
domain层:
package com.shuai.domain;
import lombok.Data;
@Data
public class People {
private String name;
private Integer age;
}
service层的实现类:由于没有复习到注解,这里通过set注入的形式将mapper注入到实现类中
package com.shuai.service.impl;
import com.shuai.domain.People;
import com.shuai.mapper.PeopleMapper;
import com.shuai.service.PeopleService;
import java.util.List;
public class PeopleServiceImpl implements PeopleService {
private PeopleMapper peopleMapper;
public void setPeopleMapper(PeopleMapper peopleMapper) {
this.peopleMapper = peopleMapper;
}
public List<People> show() {
return peopleMapper.show();
}
}
mapper层:
package com.shuai.mapper;
import com.shuai.domain.People;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface PeopleMapper {
@Select("select * from people")
List<People> show();
}
最主要的是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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源,连接数据库-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mypeople?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="3041"></property>
</bean>
<!--设置工厂,当创建工厂的时候,配置文件已经加载好了,所以这里需要关联配置好的数据源-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--配置扫描mapper的功能,扫描后要把扫描好的东西传给sql的工厂-->
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shuai.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
<!--配置bean,由于sql已经存在peopleMapper,所以,在该bean下设置set方法可以直接依赖注入-->
<bean id="peopleService" class="com.shuai.service.impl.PeopleServiceImpl">
<property name="peopleMapper" ref="peopleMapper"></property>
</bean>
</beans>
测试类:
import com.shuai.domain.People;
import com.shuai.service.impl.PeopleServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class test {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
PeopleServiceImpl peopleService= applicationContext.getBean("peopleService", PeopleServiceImpl.class);
List<People> peopleList= peopleService.show();
for (People people : peopleList) {
System.out.println(people);
}
}
}
网友评论