为什么枚举要实现接口?
272
2022-10-18
详解Spring如何整合Mybatis
第一步
导入相关jar包
第二步
编写配置文件
resources下:
spring-config.xml,此配置文件下,连接数据库,创建SqlSessionFactory
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:aop="http://springframework.org/schema/aop" xmlns:context="http://springframework.org/schema/context" xsi:schemaLocation="http://springframework.org/schema/beans https://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/context https://springframework.org/schema/context/spring-context.xsd http://springframework.org/schema/aop https://springframework.org/schema/aop/spring-aop.xsd">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:aop="http://springframework.org/schema/aop"
xmlns:context="http://springframework.org/schema/context"
xsi:schemaLocation="http://springframework.org/schema/beans
https://springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/context
https://springframework.org/schema/context/spring-context.xsd
http://springframework.org/schema/aop
https://springframework.org/schema/aop/spring-aop.xsd">
mybatis-config.xml,下边 mybatis 的配置在上边 spring-config.xml 也可以,但是为了更加清晰,职责明确,把别名配置放在了mybatis-config.xml 中配置了。
<smjDeBuNpp;/configuration>
实体类User
package com.lxc.domain;
import lombok.Data;
@Data
public class User {
private String name;
private String password;
}
UserMapper 接口
package com.lxc.dao;
import com.lxc.domain.User;
import java.util.List;
public interface UserMapper {
public List
}
UserMapperImp 实现接口
package com.lxc.dao;
import com.lxc.domain.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
// 《实现接口的类 UserMapperImp》
// 需要把这个类注入到Spring中去。
public class UserMapperImp implements UserMapper{
// 我们所有操作都是用sqlSession 来执行的
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List
UserMapper userMapper = sqlSession.getMapper(UserMapphttp://er.class);
return userMapper.getList();
}
}
UserMapper.xml
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from mybatis
第三步
测试
import com.lxc.dao.UserMapper;
import com.lxc.domain.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
UserMapper userMapper = ctx.getBean("userMapper", UserMapper.class);
for (User item : userMapper.getList()) {
System.out.println(item);
}
}
}
输出:
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~