1、首先新建一个java web的项目”web project“,命名为”MySpringIBatis“
2、右键新建的”MySpringIBatis“,选择“MyEclipse”中的 Add spring capbilities,myeclipse会自动勾选“spring 3.0 core Libraries”,需要再把“spring 3.0 web Libraries”勾选上,点击“确定”即可。这时就会在工程里面自动加上了spring mvc的包,myeclipse10不需要你再额外导入spring mvc的包。
3、导入iBATIS相关的包,主要就是三个包,附件的程序里有
4、把WebRoot \ WEB-INF \ web.xml文件改成下面这个
<span style="font-size:18px;"><pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Demo2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conf/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Demo2</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app></span>
5、在WebRoot \ WEB-INF下新建一个conf文件,在conf文件中新建一个“applicationContext.xml”文件,并把内容改为下列内容:
<span style="font-size:18px;"><?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="action" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
</bean>
</beans></span>
5、在WebRoot \ WEB-INF下新建一个views文件,文件中建立两个JSP文件。分别命名为:createSuccess和register。
createSuccess.jsp内容为:
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>创建成功</title>
</head>
<body>
用户 ${stu.name} 创建成功。
</body>
</html></span>
register.jsp内容为:
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>新增用户</title>
</head>
<body>
<form method="post" action='<c:url value="/student.html"/>'>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>性別:</td>
<td><input type="text" name="sex"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="提交"/></td>
</tr>
</table>
</form>
</body>
</html></span>
6、在src下面建立四个包文件,分别命名为:action,dao,entity ,impl
7、在entity下建立一个SqlMap.properties文件,内容为:
<span style="font-size:18px;">driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student
username=root
password=123456</span>
其中url为你的数据库的地址,用户名和密码分别为你数据库的用户名和密码,可参考我的另外一篇文章“JDBC连接各种数据库的字符串"
在entity下建立一个SqlMapConfig.xml文件,内容为:
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- 引用JDBC属性的配置文件 -->
<properties resource="entity/SqlMap.properties" />
<!-- 使用JDBC的事务管理 -->
<transactionManager type="JDBC">
<!-- 数据源 -->
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}" />
<property name="JDBC.ConnectionURL" value="${url}" />
<property name="JDBC.Username" value="${username}" />
<property name="JDBC.Password" value="${password}" />
</dataSource>
</transactionManager>
<!-- 这里可以写多个实体的映射文件 -->
<sqlMap resource="entity/student.xml" />
</sqlMapConfig></span>
在entity下建立一个student.xml文件,内容为:
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap>
<!-- 通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名 -->
<typeAlias alias="Student" type="entity.student" />
<!-- 这样以后改了sql,就不需要去改java代码了 -->
<!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->
<select id="selectAllStudent" resultClass="Student">
select * from
student
</select>
<!-- parameterClass表示参数的内容 -->
<!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->
<select id="selectStudentById" parameterClass="int" resultClass="Student">
select * from student where id=#id#
</select>
<!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->
<select id="selectStudentByName" parameterClass="String"
resultClass="Student">
select name,sex from student where name like
'%$name$%'
</select>
<insert id="addStudent" parameterClass="Student">
insert into
student(name,sex) values
(#name#,#sex#);
<selectKey resultClass="int" keyProperty="id">
select @@identity as inserted
<!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->
<!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->
<!-- mssql:select @@IDENTITY as value -->
<!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->
<!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。
有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->
</selectKey>
</insert>
<delete id="deleteStudentById" parameterClass="int">
<!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->
<!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 -->
delete from student where id=#id#
</delete>
<update id="updateStudent" parameterClass="Student">
update student set
name=#name#,sex=#sex# where id=#id#
</update>
</sqlMap></span>
<span style="font-size:18px;">package entity;
public class student {
private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String toString(){
return (id+","+name+","+sex);
}
}
</span>
entity包的内容完成
8、打开建立的dao包,建立一个StudentDao.java,内容为:
<span style="font-size:18px;">package dao;
import java.util.List;
import entity.student;
public interface StudentDao {
public List<student> selectAllStudent();
}
</span>
<span style="font-size:18px;">package impl;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import dao.StudentDao;
import entity.student;
public class StudentImpl implements StudentDao {
private static SqlMapClient sqlMapClient = null;
// 读取配置文件
static {
try {
Reader reader = Resources
.getResourceAsReader("entity/SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<student> selectAllStudent() {
// TODO Auto-generated method stub
List<student> students = null;
try {
students = sqlMapClient.queryForList("selectAllStudent");
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
public boolean addUser(student stu) {
Object object = null;
boolean flag = false;
try {
object = sqlMapClient.insert("addStudent", stu);
// System.out.println("添加学生信息的返回值:" + object);
} catch (SQLException e) {
e.printStackTrace();
}
if (object != null) {
flag = true;
}
return flag;
}
}
</span>
9、打开建立的action包,建立一个StudentAction.java,内容为:
<span style="font-size:18px;">package action;
import impl.StudentImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import entity.student;
@Controller
@RequestMapping("/student")
public class StudentAction {
@RequestMapping("/register")
public String register() {
return "register";
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView createUser(student stu) {
ModelAndView mav = new ModelAndView();
StudentImpl studao = new StudentImpl();
studao.addUser(stu);
mav.setViewName("createSuccess");
mav.addObject("stu", stu);
return mav;
}
}
</span>
第一次发这么长的博客,逻辑有点混乱了,我也是第一次摸索着做的,可能有很多地方走弯路了,附件会上传这个demo的程序,欢迎大家指正。