[TOC]
(SpringMVC+Spring+ mybatis)
配置内容:
导入jar插件
spring 管理连接文件
sessionFactory 管理session工厂
dataSource 管理数据源
MappingScannerCongigurer 管理映射文件
实现UserDao属性注入 实现属性注入
具体操作
- spring 管理连接文件
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"> </property>
</bean>
- sessionFactory
<!--创建sessionFactory -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/wxb/mapper/*.xml"></property>
</bean>
- dataSource
<!-- 数据源 dbcp c3p0 jndi -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value=""></property>
<property name="driverClassName" value="${driver}"></property>
</bean>
- MappingScannerCongigurer
<bean id="mcf" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wxb.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
</bean>
- 实现UserDao属性注入
@Autowired
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
管理流程
控制层 管理service层
@Autowired
private UserServiceImp us;
public void setUs(UserServiceImp us) {
this.us = us;
}
注意:都需要注解
service层管理dao层
@Autowired
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
注意:都需要注解
dao层 管理映射文件
public ArrayList<User> list(User user) ;
public void save(User user);
public void update(User user);
public void delete(User user);
public int count();
通过构造方法同映射文件中的sql语句相关联(方法名)
<mapper namespace="com.wxb.dao.UserDao">
<select id="list" resultType="com.wxb.model.User" parameterType="com.wxb.model.User" >
select uid,name from user
<where>
<if test="uid!=0">
and uid=#{uid}
</if>
<if test="null!=name and ''!=name">
and name like CONCAT('%',#{name},'%')
</if>
</where>
limit #{pageIndex},#{size}
</select>
<insert id="save" parameterType="com.wxb.model.User">
insert into user (name) values(#{name})
</insert>
<delete id="delete" parameterType="com.wxb.model.User" >
delete from user <include refid="byId"></include>
</delete>
<update id="update" parameterType="com.wxb.model.User">
update user set name=#{name} <include refid="byId"></include>
</update>
<select id="count" resultType="java.lang.Integer">
select count(*) from user
</select>
<sql id="byId" >
where uid=#{uid}
</sql>
</mapper>
转发到show.jsp 页面
@RequestMapping("/show")
public String show(HttpServletRequest request, User user) {
System.out.println("我是show()方法");
// String name = request.getParameter("name");
System.out.println(user.getName());
request.getSession().setAttribute("name", user.getName());
return "/show.jsp";
回调show方法
return "redirect:show";
重定向到show.jsp 页面
return "redirect:/show.jsp";
}