springMvc入门教程2(集成mybatis和参数绑定)
源码地址:https://files.cnblogs.com/files/suzixuan/springMvcGuide.zip
数据库使用:mysql5.6
mybatis版本:mybatis-3.4.4
根据上次的项目,做了文件夹修改,整体目录如下:
1,修改spring-servlet.xml的文件目录,放在了Java Resources/resources下
web.xml文件内容修改,修改了spring-servlet.xml的加载目录
2,新添加jar包
mybatis-3.4.4.jar
mysql-connector-java-5.1.42-bin.jar
3,新增如上图的文件夹若干
4,增加web.xml中servlet拦截器,用于做静态文件解析。
5,增加mybatis的配置文件
6,添加控制器HomeController下的方法(public String Demo(Model model,@PathVariable("id") int id) )
7,建表脚本:
DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `account` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
下面主要讲解myBatis的配置
myBatis需要jar包:mybatis-3.4.4.jar,mysql-connector-java-5.1.42-bin.jar
配置文件:mysql.properties,mybatis.cfg.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=
<?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> <properties resource="mysql.properties"></properties> <typeAliases> <package name="model" /> </typeAliases> <environments default="cybatis"> <environment id="cybatis"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <package name="mapper" /> </mappers> </configuration>
建立Model类
package model; import java.io.Serializable; public class UserBean implements Serializable{ private static final long serialVersionUID = 1L; private Integer id; private String username; private String password; private Double account; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public UserBean() { super(); } public UserBean(String username, String password, Double account) { super(); this.username = username; this.password = password; this.account = account; } public UserBean(Integer id, String username, String password, Double account) { super(); this.id = id; this.username = username; this.password = password; this.account = account; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getAccount() { return account; } public void setAccount(Double account) { this.account = account; } @Override public String toString() { return "UserBean [id=" + id + ", username=" + username + ", password=" + password + ", account=" + account + "]"; } }
mapper文件:UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mapper.UserMapper"> <resultMap id="userMap" type="userbean"> <id column="id" javaType="java.lang.Integer" property="id" /> <result column="username" javaType="java.lang.String" property="username" /> <result column="password" javaType="java.lang.String" property="password" /> <result column="account" javaType="java.lang.Double" property="account" /> </resultMap> <insert id="insertUser" keyProperty="id" useGeneratedKeys="true"> insert into t_user (username,password,account) values (#{username},#{password},#{account}) </insert> <update id="updateUser"> update t_user set username=#{username},password=#{password},account=#{account} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from t_user where id=#{id} </delete> <select id="selectUserById" parameterType="int" resultMap="userMap"> select * from t_user where id=#{id} </select> <select id="selectAllUser" resultMap="userMap"> select * from t_user </select> <select id="selectUserByNameAccount" resultType="model.UserBean"> select * from t_user <where> <if test="name!=null and name!=''"> and username like '%' #{name} '%' </if> <if test="account!=null"> and account>#{account} </if> </where> </select> </mapper>
建立UserMapper接口:
package mapper;
import java.util.List;
import java.util.Map;
import model.UserBean;
/**
* @author huidong
*
*/
public interface UserMapper {
/**
* 新增用戶
* @param user
* @return
* @throws Exception
*/
public int insertUser(UserBean user) throws Exception;
/**
* 修改用戶
* @param user
* @param id
* @return
* @throws Exception
*/
public int updateUser (UserBean user,int id) throws Exception;
/**
* 刪除用戶
* @param id
* @return
* @throws Exception
*/
public int deleteUser(int id) throws Exception;
/**
* 根据id查询用户信息
* @param id
* @return
* @throws Exception
*/
public UserBean selectUserById(int id) throws Exception;
/**
* 查询所有的用户信息
* @return
* @throws Exception
*/
public List<UserBean> selectAllUser() throws Exception;
/**
* 根据姓名和密码查询用户信息
* @return
* @throws Exception
*/
public List<UserBean> selectUserByNameAccount(Map<String,Object> map) throws Exception;
}
建立DBTools:
package tools; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DBTools { public static SqlSessionFactory sessionFactory; static{ try { //使用MyBatis提供的Resources类加载mybatis的配置文件 Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); //构建sqlSession的工厂 sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } //创建能执行映射文件中sql的sqlSession public static SqlSession getSession(){ return sessionFactory.openSession(); } }
建立Servic类,做测试
package service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.jdbc.SQL; import org.apache.ibatis.session.SqlSession; import model.UserBean; import tools.DBTools; import mapper.UserMapper; public class UserService { /** * 新增用户 */ private static void insertUser() { try (SqlSession session = DBTools.getSession()) { UserBean user = new UserBean("苏子2", "123", 500.0); session.insert("insertUser", user); session.commit(); } } /** * 删除用户 */ private static void deleteUser() { SqlSession session = DBTools.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); try { mapper.deleteUser(1); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } /** * 根据id查询用户 */ public static UserBean selectUserById(int id) { SqlSession session = DBTools.getSession(); UserBean user = session.selectOne("selectUserById", id); if (user == null) { System.out.println("user不存在"); } else { System.out.println(user.toString()); } session.close(); return user; } /** * 查询所有的用户 */ private static void selectAllUser() { SqlSession session = DBTools.getSession(); List<UserBean> list = session.selectList("selectAllUser"); for (UserBean user : list) { System.out.println(user.toString()); } session.close(); } private static void selectUserByQuery() { SqlSession session = DBTools.getSession(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "2"); map.put("account", 400); UserMapper mapper = session.getMapper(UserMapper.class); try { List<UserBean> list = mapper.selectUserByNameAccount(map); for (UserBean user : list) { System.out.println(user.toString()); } if (list == null || list.size() <= 0) { System.out.println("数据集为空"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
讲解三个注解:
@RequestMapping,用来映射请求的url地址
@RequestParam,绑定单个请求数据,可以是URL中的数据,表单提交的数据或上传的文件;
@PathVariable,绑定URL模板变量值;
感谢网友们的分享,能让我一步步学习mvc和mybatis。
http://www.cnblogs.com/liukemng/p/3729071.html