Spring mvc + mybaits

 
 

项目结构图

Spring mvc + mybaits - 口袋里的小龙 - 口袋里的小龙
首先配置spring支持 web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 配置spring支持 --> <servlet> <servlet-name>springapp</servlet-name> <!-- 配置核心控制器 --> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springapp</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>

<display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

 
 
配置spring配置文件 springapp-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- 前缀 --> <property name="prefix" value="/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <!-- 数据库驱动 --> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property> <!-- 连接字符串 --> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property> <!-- 用户名 --> <property name="username" value="system"></property> <!-- 密码 --> <property name="password" value="orcl"></property> </bean> <!-- 配置sessionFactory工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:myBatis_config.xml"></property> </bean> <!--配置模板类 这个是mybatis提供的一个辅助模板 --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"></constructor-arg> </bean>

<bean id="userDao" class="com.dragon.dao.impl.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> <property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property> </bean> <bean name="/index.action" class="com.dragon.controller.LoginController"> <property name="userDaoImpl" ref="userDao"></property> </bean> <bean name="/insert.action" class="com.dragon.controller.InsertController"> <property name="userDaoImpl" ref="userDao"></property> </bean> </beans>

配置myBatis_config.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> <settings > <!-- 不启用延迟加载 --> <setting name="lazyLoadingEnabled" value="false"/> </settings> <!-- 为bean 起别名 --> <typeAliases> <typeAlias type="com.dragon.entity.User" alias="User"/> </typeAliases> <!-- 配置orm映射 --> <mappers> <mapper resource="com/dragon/entity/user_mapper.xml"/> </mappers> </configuration>

 
  
实体类

package com.dragon.entity;

import java.io.Serializable; /** * 用户实体类 * @author Administrator * */ public class User implements Serializable { public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public static long getSerialversionuid() { return serialVersionUID; } /** * */ private static final long serialVersionUID = 1L; private int userId; private String userName; private String userPassword; public User() { super(); }

}

实体类的映射文件

user_mapper.xml<wbr></wbr>

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="com.dragon.entity.User"> <!-- 配置orm映射 确保数据库中的列能和bean中的列相对应 --> <resultMap type="User" id="user_orm"> <id property="userId" column="user_id"/> <result property="userName" column="user_name"></result> <result property="userPassword" column="user_password"></result> </resultMap> <!-- 查询全部的数据 --> <select id="selectAll_user" parameterType="User" resultMap="user_orm" > SELECT user_id , user_name , user_password FROM UserInfo </select> <!-- 根据编号查询单个的数据 --> <select id="selectById" parameterType="int" resultMap="user_orm"> SELECT * FROM UserInfo WHERE user_id = #{userId} </select> <!-- 根据名称迷糊查询数据 --> <select id="selectByObj" parameterType="String" resultMap="user_orm"> SELECT * FROM UserInfo WHERE user_name LIKE #{userName} </select> <insert id="insertUser" parameterType="User" > INSERT INTO UserInfo VALUES (#{userId},#{userName},#{userPassword}) </insert> <update id="updateUser" parameterType="User" > UPDATE UserInfo SET user_name = #{userName}, user_password = #{userPassword} WHERE user_id = #{userId} </update> <delete id="deleteUser" parameterType="User" > DELETE FROM UserInfo WHERE user_id=#{userId} </delete> </mapper>

userDao

package com.dragon.dao;

import java.util.List;

import com.dragon.entity.User;

public interface UserDao { /** * 获得全部的方法 * @return */ public abstract List<User> getAll(); /** * 根据编号查询 * @param id * @return */ public abstract User getById(int id); /** * 更新 * @param user * @return */ public abstract int updateUser(User user); /** * 保存 * @param user * @return */ public abstract int saveUser(User user); /** * 删除 * @param user * @return */ public abstract int deleteUser(User user); }

impl

package com.dragon.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import com.dragon.dao.UserDao;
import com.dragon.entity.User;
public class UserDaoImpl implements UserDao {
/**
 * sessionFactory工厂的方法来获得对象实例
 */
private SqlSessionFactory sqlSessionFactory;
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
/**
 * 通过mybatis提供的模板类来实现
 */
private SqlSessionTemplate sqlSessionTemplate;
public SqlSessionTemplate getSqlSessionTemplate() {
return sqlSessionTemplate;
}
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
/**
 * 查询全部的方法
 */
public List<User> getAll() {
// TODO Auto-generated method stub
List<User> userList = null;
SqlSession session1 = null;
try {
//获得session对象
//SqlSession session = this.getSqlSessionFactory().openSession();
//userList = session.selectList("selectAll_user");
///////////////使用sqlSessionTemplate模板类实现
session1 = this.getSqlSessionTemplate().getSqlSessionFactory().openSession();
//根据sql语句查询
userList = session1.selectList("selectAll_user");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(session1.getConnection().isClosed()==false){
session1.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return userList;
}
public User getById(int id) {
// TODO Auto-generated method stub
User user = null;
try {
SqlSession session1 = this.getSqlSessionTemplate().getSqlSessionFactory().openSession();
user = session1.selectOne("selectById",1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return user;
}
public int updateUser(User user) {
// TODO Auto-generated method stub
int result = 0;
try {
SqlSession session1 = this.getSqlSessionTemplate().getSqlSessionFactory().openSession();
result= session1.update("updateUser", user);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
public int saveUser(User user) {
// TODO Auto-generated method stub
int result = 0;
try {
SqlSession session1 = this.getSqlSessionTemplate().getSqlSessionFactory().openSession();
result= session1.insert("insertUser", user);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
public int deleteUser(User user) {
// TODO Auto-generated method stub
int result = 0;
try {
SqlSession session1 = this.getSqlSessionTemplate().getSqlSessionFactory().openSession();
result= session1.delete("deleteUser", user);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
}

controller类  查询全部

package com.dragon.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller;

import com.dragon.dao.UserDao; import com.dragon.entity.User;

public class LoginController implements Controller { private UserDao userDaoImpl; public UserDao getUserDaoImpl() { return userDaoImpl; }

public void setUserDaoImpl(UserDao userDaoImpl) { this.userDaoImpl = userDaoImpl; }

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub //ApplicationContext context = new ClassPathXmlApplicationContext("springapp-servlet.xml"); List<User> userList = this.userDaoImpl.getAll(); System.out.println("一共有数据------------------------"); System.out.println(userList.size()); for (int i = 0; i < userList.size(); i++) { System.out.println(userList.get(i).getUserName()); } return new ModelAndView("index") ; }

}

你可能感兴趣的:(spring,mvc)