SpringMVC简单整合Mybatis

maven依赖

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

spring 配置文件

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="mybatisSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis/mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mybatis/mapper/**/*.xml"></property>
    </bean>

mybatis.mybatis.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>
    <!-- 别名 -->
    <typeAliases>
        <package name="models" />
    </typeAliases>
</configuration>


mybatis.mapper.UserMapper.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="mybatis.mapper.UserMapper">
       <select id="getUsername" resultType="String">
              select username from s_user where id=#{id}
       </select>
</mapper>

controller

@Controller
@RequestMapping("/")
public class HelloController {

    @Autowired
    private UserServices userServices;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView printWelcome(HttpServletRequest request) {

        userServices.getUsername();
        return new ModelAndView("index");
    }
}

services

@Service
public class UserServices {

    public UserServices() {
    }

    @Autowired
    private SqlSessionFactory mybatisSessionFactory;

    public void getUsername() {
        SqlSession session = mybatisSessionFactory.openSession();
        String username = (String) session.selectOne("mybatis.mapper.UserMapper.getUsername", 1);
        System.out.println("mybatis:"+username);
    }
}



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页