依赖jar:
Spring整合MyBatis依赖jar
结构:
项目结构
applicationContext.xml:
<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">
<!--数据源封装类,数据源:获取数据库连接,spring-jdbc.jar中-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:oracle:thin:@192.168.72.3:1521:orcl"></property>
<property name="username" value="scott"></property>
<property name="password" value="tiger"></property>
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
</bean>
<!--配置sqlSession工厂类-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--扫描器,相当于MyBatis.xml中mapper下的package标签,扫描后会给对应接口创建对象-->
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com"/>
<!--与factory关联org.mybatis.spring.mapper.MapperScannerConfigurer-->
<property name="sqlSessionFactoryBeanName" value="factory"/>
</bean>
<bean id="empService" class="com.Service.Impl.EmpServiceImpl">
<property name="empMapper" ref="empMapper"></property>
</bean>
</beans>
EmpMapper:
package com.Mapper;
import com.pojo.Emp;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface EmpMapper {
@Select("select * from emp")
public List<Emp> selAll();
}
EmpServiceImpl:
package com.Service.Impl;
import com.Mapper.EmpMapper;
import com.Service.EmpService;
import com.pojo.Emp;
import java.util.List;
public class EmpServiceImpl implements EmpService {
private EmpMapper empMapper;
public EmpMapper getEmpMapper() {
return empMapper;
}
public void setEmpMapper(EmpMapper empMapper) {
this.empMapper = empMapper;
}
@Override
public List<Emp> selAll() {
return empMapper.selAll();
}
}
EmpService:
package com.Service;
import com.pojo.Emp;
import java.util.List;
public interface EmpService {
List<Emp> selAll();
}
Test:
package com;
import com.Service.EmpService;
import com.pojo.Emp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Test {
public static void main(String[] args) {
// ClassPathXmlApplicationContext默认去classes文件夹根目录下寻找文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
EmpService empService = ac.getBean("empService", EmpService.class);
List<Emp> emps = empService.selAll();
for (Emp emp : emps) {
System.out.println(emp);
}
}
}
网友评论