需求:根据用户id查询用户信息
一.配置
1.mybatis.xml
<configuration>
<!-- 配置别名 -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="com.steven.ssm.po"/>
</typeAliases>
<mappers>
<mapper resource="sqlmap/UserMapper.xml"/>
</mappers>
</configuration>
2.applicationContext-dao.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 加载db.properties -->
<context:property-placeholder location="config/mybatis/db.properties" />
<!-- 1.配置数据源(c3p0数据库连接池)-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 基础配置 -->
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 2.配置sqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据库源 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="config/mybatis/mybatis.xml" />
</bean>
<!-- 3.配置userDaoImpl -->
<bean id="userDaoImpl" class="com.steven.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
配置数据库源、sqlSessionFactory对象以及UserDaoImpl的bean。
二.映射
<mapper namespace="com.steven.ssm.mapper.UserMapper">
<select id="findUserById" resultType="User" parameterType="int">
select * from user where id=#{id}
</select>
</mapper>
三.接口以及接口实现类
public interface UserDao {
User findUserById(int id) throws Exception;
}
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("findUserById",1);
return user;
}
}
四.po类编写
public class User {
//属性名要和数据库表的字段对应
private int id;
private String username;// 用户姓名
private String sex;// 性别
private String birthday;// 生日
private String address;// 地址
//get和set方法......
}
五.测试
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/spring/applicationContext-dao.xml");
UserDaoImpl userDaoImpl = (UserDaoImpl) applicationContext.getBean("userDaoImpl");
User user = userDaoImpl.findUserById(1);
System.out.println(user);