MyBatis项目学习笔记


MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录

@Controller  控制层,就是我们的action层

@Service   业务逻辑层,就是我们的service或者manager层

@Repository  持久层,就是我们常说的DAO层

@Component (字面意思就是组件),它在你确定不了事哪一个层的时候使用。

其实,这四个注解的效果都是一样的,Spring都会把它们当做需要注入的Bean加载在上下文中;

但是在项目中,却建议你严格按照除Componen的其余三个注解的含义使用在项目中。这对分层结构的web架构很有好处!!

目录:

 

项目所需Jar包:

 

连接数据库SQL语句:

CREATE DATABASE manpower;

USE manpower;

CREATE TABLE `user` (

  `id` INT(10) NOT NULL AUTO_INCREMENT,

  `name` VARCHAR(20) DEFAULT NULL,

  `sex` VARCHAR(10) DEFAULT NULL,

  `birthday` DATE DEFAULT NULL,

  `feature` VARCHAR(10) DEFAULT NULL,

  `job` VARCHAR(10) DEFAULT NULL,

  `jobname` VARCHAR(15) DEFAULT NULL,

  `education` VARCHAR(20) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

INSERT INTO USER(id,NAME,sex,birthday,feature,job,jobname,education)

    VALUES(1,"张三","","1996-8-8","党员","IT","程序员","本科")

   INSERT INTO USER(id,NAME,sex,birthday,feature,job,jobname,education)

    VALUES(3,"李四","","1992-8-8","党员","教育","老师","本科")

jdbc.properties数据库文件配置 :

driver=com.mysql.jdbc.Driver

url = jdbc\:mysql\://localhost\:3306/manpower

username = root

password = 1234

log4j.properties日志文件配置:

# Global logging configuration

log4j.rootLogger=DEBUG, stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

实体类:

package cn.wallance.domain;

public class User {

private int id;

private String name;

private String sex;

private String birthday;

private String feature;

private String job;

private String jobname;

private  String education;

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 getBirthday()

{

return birthday;

}

public void setBirthday(String birthday)

{

this.birthday = birthday;

}

public String getFeature()

{

return feature;

}

public void setFeature(String feature)

{

this.feature = feature;

}

public String getJob()

{

return job;

}

public void setJob(String job)

{

this.job = job;

}

public String getJobname()

{

return jobname;

}

public void setJobname(String jobname)

{

this.jobname = jobname;

}

public String getEducation()

{

return education;

}

public void setEducation(String education)

{

this.education = education;

}

}

Dao接口:

package cn.wallance.dao;

 

import java.util.List;

 

import cn.wallance.domain.User;

 

public interface IUserDao {

//全查询

public abstract List<User> selectAll();

//插入数据

public abstract int addUser(User user);

//删除数据

public abstract int deleteUser(int id);

//查询一个用户

public abstract User selectone(int id);

//修改数据

public abstract int updateUser(User user);

}

 Dao接口实现类:

  package cn.wallance.dao;

import java.util.List;

import javax.annotation.Resource;

Import

org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import org.springframework.stereotype.Repository;

import cn.wallance.domain.User;

@Repository("userDao")//注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。

public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao {

@Resource

    public void setSuperSessionFactory(SqlSessionFactory sessionFactory){

    this.setSqlSessionFactory(sessionFactory);

    }

public List<User> selectAll() {

// TODO Auto-generated method stub

List<User> users = this.getSqlSession().selectList("getUser");

return users;

}

@Override

public int addUser(User user) {

// TODO Auto-generated method stub

int add=this.getSqlSession().insert("adduser",user);

return add;

}

@Override

public int deleteUser(int id)

{

// TODO Auto-generated method stub

int del=this.getSqlSession().delete("delete",id);

return del;

}

@Override

public User selectone(int id)

{

// TODO Auto-generated method stub

User sl=this.getSqlSession().selectOne("selectone",id);

return sl;

}

@Override

public int updateUser(User user)

{

// TODO Auto-generated method stub

int up=this.getSqlSession().update("update",user);

return up;

}

}

Mapper映射文件:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.wallance.mapping.classMapper">

    <select id="getUser" resultType="cn.wallance.domain.User">

        select * from user

    </select>

    <insert id="adduser" parameterType="cn.wallance.domain.User">

    insert into user(name,sex,birthday,feature,job,jobname,education)

    values(#{name},#{sex},#{birthday},#{feature},#{job},#{jobname},#{education})

    </insert>

       <delete id="delete" parameterType="int">

       delete from user where id=#{id}

       </delete>

       <select id="selectone" parameterType="int" resultType="cn.wallance.domain.User">

       select * from user where id=#{id}

       </select>

       <update id="update" parameterType="cn.wallance.domain.User">

       update user set name=#{name},sex=#{sex},birthday=#{birthday},

       feature=#{feature},job=#{job},jobname=#{jobname},education=#{education}

        where id=#{id}

       </update>

</mapper>

业务逻辑层service接口:

package cn.wallance.service;

import java.util.List;

import cn.wallance.domain.User;

public interface IUserService {

public abstract List<User> selectAll();

    public abstract  int addUser(User user);

   public abstract int deleteUser(int id);

   public abstract User selectone(int id);

public abstract int updateUser(User user);

}

业务逻辑层service接口实现类:

package cn.wallance.service;

 

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.wallance.dao.IUserDao;

import cn.wallance.domain.User;

@Service("userService")

public class UserServiceImpl implements IUserService {

private IUserDao userDao;

public IUserDao getUserDao() {

return userDao;

}

    @Resource

public void setUserDao(IUserDao userDao) {

this.userDao = userDao;

}

@Override

public List<User> selectAll() {

// TODO Auto-generated method stub

return userDao.selectAll();

}

 

@Override

public int  addUser(User user) {

// TODO Auto-generated method stub

return userDao.addUser(user);

}

@Override

public int deleteUser(int id)

{

// TODO Auto-generated method stub

return userDao.deleteUser(id);

}

@Override

public User selectone(int id)

{

// TODO Auto-generated method stub

return userDao.selectone(id);

}

@Override

public int updateUser(User user)

{

// TODO Auto-generated method stub

return userDao.updateUser(user);

}

}

Controller层(用于服务客户端请求的服务端):

package cn.wallance.web;

 

import java.util.Date;

import java.util.List;

 

import javax.annotation.Resource;

import javax.swing.Spring;

 

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

 

import cn.wallance.domain.User;

import cn.wallance.service.IUserService;

 

@Controller

public class HomeController {

private IUserService userService;

public IUserService getUserService() {

return userService;

}

    @Resource

public void setUserService(IUserService userService) {

this.userService = userService;

}

 

@RequestMapping(value="/home",method=RequestMethod.GET)

public String home(Model model){

List<User> users = userService.selectAll();

model.addAttribute("users", users);

return "home";

}

@RequestMapping(value="/insert",method=RequestMethod.GET)

public String insert(Model model){

 

return "insert";

}

@RequestMapping(value="/insert",method=RequestMethod.POST)

public String insert(String name, String sex, String birthday,

String feature, String job,String jobname,String education){

 User user=new User();

 user.setName(name);

 user.setSex(sex);

 user.setBirthday(birthday);

 user.setFeature(feature);

 user.setJob(job);

 user.setJobname(jobname);

 user.setEducation(education);

 userService.addUser(user);

 return "redirect:home";

 }

@RequestMapping(value="/delete",method=RequestMethod.GET)

public String delete(Model model,int id){

userService.deleteUser(id);

return "redirect:home";

}

@RequestMapping(value="/update",method=RequestMethod.GET)

public String update(Model model,int id){

User user=userService.selectone(id);

model.addAttribute("user",user);

return "update";

}

@RequestMapping(value="/update",method=RequestMethod.POST)

public String update(int id,User user){

userService.updateUser(user);

return "redirect:home";

}

}

school-mybatis.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:mybatis="http://mybatis.org/schema/mybatis-spring"  

       xmlns:context="http://www.springframework.org/schema/context"  

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  

       http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd  

       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  

     <!-- 自动扫描 -->  

    <context:component-scan base-package="cn.wallance" />  

    <!-- 引入配置文件 -->  

    <bean id="propertyConfigurer"  

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

        <property name="location" value="classpath:jdbc.properties" />  

    </bean>  

  

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  

        destroy-method="close">  

        <property name="driverClassName" value="${driver}" />  

        <property name="url" value="${url}" />  

        <property name="username" value="${username}" />  

        <property name="password" value="${password}" />  

        

        <!-- 配置连接池的初始值 -->

<property name="initialSize" value="1" />

<!-- 连接池的最大值 -->

<!-- <property name="maxActive" value="500"/> -->

<!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 -->

<!-- <property name="maxIdle" value="2"/> -->

<!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 -->

<property name="minIdle" value="1" />

<property name="maxActive" value="100" />

<property name="maxIdle" value="20" />

<property name="maxWait" value="1000" /> 

    </bean>  

    

    <!-- springMyBatis完美整合,不需要mybatis的配置映射文件 -->  

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  

        <property name="dataSource" ref="dataSource" />  

        <!-- 自动扫描mapping.xml文件 -->  

        <property name="mapperLocations" value="classpath:cn/wallance/mapping/*.xml"></property>  

    </bean>  

  

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  

        <property name="basePackage" value="cn.wallance.dao" />  

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  

    </bean>  

  

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  

    <bean id="transactionManager"  

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  

        <property name="dataSource" ref="dataSource" />  

    </bean>    

         

</beans>

school-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:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

      <!-- 开启注解 -->

      <mvc:annotation-driven/>

      <!-- 设置组件扫描的基础包 -->

      <context:component-scan base-package="cn.wallance.web"/>

      

      <!-- 配置视图解析器 -->

      <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">

          <property name="prefix" value="/WEB-INF/school/" />

          <property name="suffix" value=".jsp" />

      </bean>

</beans>

web.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

 

  <!-- 配置DispatcherServlet -->

  <servlet>

     <servlet-name>school</servlet-name>

     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  </servlet>

  <servlet-mapping>

     <servlet-name>school</servlet-name>

     <url-pattern>/</url-pattern>

  </servlet-mapping>

  

 

  <!-- Spring 的监听器可以通过这个上下文参数来获取school-mybatis.xml的位置 -->

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:school-mybatis.xml</param-value>   

  </context-param>

  

    <!-- 创建Spring的监听器 -->

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

  <!-- 创建字符过滤器 -->

  <filter>

     <filter-name>CharacterFilter</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>

  </filter>

  

  <filter-mapping>

      <filter-name>CharacterFilter</filter-name>

      <url-pattern>/*</url-pattern>

  </filter-mapping>

 

</web-app>

JSp页面(home.jsp)

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">    

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

  </head>

  

  <body>

  <table border="6">

<caption>人员信息表</caption>

       <tr>

        <td>编号</td>

        <td>姓名</td>

        <td>性别</td>

        <td>出生日期</td>

        <td>政治面貌</td>

        <td>职务</td>

        <td>职称</td>

        <td>最高学历</td>

        <td>操作</td>

       </tr>

       <c:forEach items="${users}" var="user">

       <tr>

       <td>${user.id}</td>

       <td>${user.name}</td>

       <td>${user.sex}</td>

       <td>${user.birthday}</td>

       <td>${user.feature}</td>

       <td>${user.job}</td>

       <td>${user.jobname}</td>

       <td>${user.education}</td>

       <td><a href="delete?id=${user.id}">删除</a>/<a href="update?id=${user.id}">更改</a>/<a href="">注销</a></td>

      

       </tr>

       </c:forEach>

    </table>

    <a href="insert">新增人员</a>

  </body>

</html>

 

Insert.jsp(添加页面):

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">    

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

  </head>

  <body>

  <table border="6">

<caption>人员信息表</caption>

       <tr>

        <td>编号</td>

        <td>姓名</td>

        <td>性别</td>

        <td>出生日期</td>

        <td>政治面貌</td>

        <td>职务</td>

        <td>职称</td>

        <td>最高学历</td>

        <td>操作</td>

       </tr>

       <c:forEach items="${users}" var="user">

       <tr>

       <td>${user.id}</td>

       <td>${user.name}</td>

       <td>${user.sex}</td>

       <td>${user.birthday}</td>

       <td>${user.feature}</td>

       <td>${user.job}</td>

       <td>${user.jobname}</td>

       <td>${user.education}</td>

       <td><a href="delete?id=${user.id}">删除</a>/<a href="update?id=${user.id}">更改</a>/<a href="">注销</a></td>

      

       </tr>

       </c:forEach>

    </table>

    <a href="insert">新增人员</a>

  </body>

</html>

update.jsp(修改页面):

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert title here</title>

</head>

<body>

<table border="6">

<caption>人员信息表</caption>

       <tr>

        <td>人员ID:${user.id}</td>

       </tr>

       <tr>

       <td>编号</td>

        <td>姓名</td>

        <td>性别</td>

        <td>出生日期</td>

        <td>政治面貌</td>

        <td>职务</td>

        <td>职称</td>

        <td>最高学历</td>

        <td>操作</td>

       </tr>

       <tr>

       <form action="update" method="post">

       <td><input type="hidden" name="id" value="${user.id}"></td>

        <td><input type="text" name="name" value="${user.name}"></td>

        <td><input type="text" name="sex" value="${user.sex}"></td>

         <td><input type="text" name="birthday" value="${user.birthday}"></td>

          <td><input type="text" name="feature" value="${user.feature}"></td>

           <td><input type="text" name="job" value="${user.job}"></td>

            <td><input type="text" name="jobname" value="${user.jobname}"></td>

             <td><input type="text" name="education" value="${user.education}"></td>

     <td><input type="submit" value="修改"></td>

      </form>

       </tr>

          

</table>

</body>

</html>

 

 

 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

 

 

 

 

猜你喜欢

转载自blog.csdn.net/qq_41224638/article/details/80548698