mybatis複習小專案
學完mybatis做的一個小專案,包含檢視老師資訊和新增老師資訊的功能,整個專案結構有截圖,每個檔案程式碼下面都有,之外的相關就是資料庫表了,在此沒有做,懂資料庫的很簡單的一張表自己弄吧,不懂得暫時就犯不著瞭解mybatis了
Teacher.java
---------------------------------------程式碼開始-------------------------------------------
package com.entity;
public class Teacher {
//javaBean是有預設建構函式的只含有set get tostring的java類
private int teaId;
private String teaName;
private int teaAge;
private int gradeId;
public int getTeaId() {
return teaId;
}
public void setTeaId(int teaId) {
this.teaId = teaId;
}
public String getTeaName() {
return teaName;
}
public void setTeaName(String teaName) {
this.teaName = teaName;
}
public int getTeaAge() {
return teaAge;
}
public void setTeaAge(int teaAge) {
this.teaAge = teaAge;
}
public int getGradeId() {
return gradeId;
}
public void setGrade(int gradeId) {
this.gradeId = gradeId;
}
@Override
public String toString() {
return "Teacher [teaId=" + teaId + ", teaName=" + teaName + ", teaAge=" + teaAge + ", grade=" + gradeId
+ "]";
}
}
---------------------------------------程式碼結束-------------------------------------------
TeacherDAO.java
---------------------------------------程式碼開始-------------------------------------------
package com.dao;
import java.util.List;
import com.entity.Teacher;
public interface TeacherDAO {
public List<Teacher> getAll();
public int add(Teacher tea);
}
---------------------------------------程式碼結束-------------------------------------------
TeacherDAOImpl.java
---------------------------------------程式碼開始-------------------------------------------
package com.dao.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.dao.TeacherDAO;
import com.entity.Teacher;
public class TeacherDAOImpl implements TeacherDAO{
@Override
public List<Teacher> getAll() {
SqlSession session=BaseDAO.getSession();
TeacherDAO dao=session.getMapper(TeacherDAO.class);
List<Teacher> teaList=dao.getAll();
session.close();
return teaList;
}
@Override
public int add(Teacher tea) {
SqlSession session=BaseDAO.getSession();
TeacherDAO dao=session.getMapper(TeacherDAO.class);
int count=dao.add(tea);
//資料庫內容變動一定要加上commit()
session.commit();
session.close();
return count;
}
}
---------------------------------------程式碼結束-------------------------------------------
BaseDAO.java
---------------------------------------程式碼開始-------------------------------------------
package com.dao.impl;
import java.io.IOException;
import java.io.InputStream;
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 BaseDAO {
//這裡涉及到try{}中的內容不管是定義還是賦值,在之後使用的時候因為考慮的是try{}中內容一定
//報錯的情況,編譯的時候會按try{}之前的定義和賦值來使用,執行的時候才會使用try{}中的內容
static final String CONFIG_FILE="mybaits-config.xml";
static SqlSessionFactory factory;
static{
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
InputStream is;
try {
is = Resources.getResourceAsStream(CONFIG_FILE);
factory=builder.build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession(){
return factory.openSession();
}
}
---------------------------------------程式碼結束-------------------------------------------
TeacherMapper.xml
---------------------------------------程式碼開始-------------------------------------------
<?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="com.dao.TeacherDAO">
<select id="getAll" resultType="teacher">
select * from teacher
</select>
<insert id="add">
insert into teacher values(null,#{teaName},#{teaAge},#{gradeId})
</insert>
</mapper>
---------------------------------------程式碼結束-------------------------------------------
AddServlet.java
---------------------------------------程式碼開始-------------------------------------------
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.TeacherDAO;
import com.dao.impl.TeacherDAOImpl;
import com.entity.Teacher;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
//定義頁面的時候要寫反斜號
@WebServlet("/addTeacherServlet")
public class AddServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
TeacherDAO dao=new TeacherDAOImpl();
Teacher tea=new Teacher();
tea.setTeaName(request.getParameter("name"));
tea.setTeaAge(Integer.parseInt(request.getParameter("age")));
tea.setGrade(Integer.parseInt(request.getParameter("grade")));
dao.add(tea);
//先跳轉到servlet頁面的時候不寫反斜號
response.sendRedirect("listServlet");
}
}
---------------------------------------程式碼結束-------------------------------------------
TeacherServlet.java
---------------------------------------程式碼開始-------------------------------------------
a
package com.servlet;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.TeacherDAO;
import com.dao.impl.TeacherDAOImpl;
import com.entity.Teacher;
//頁面名字是定義在類上的,不是方法上
@WebServlet("/listServlet")
public class TeacherServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TeacherDAO dao=new TeacherDAOImpl();
List<Teacher> teaList=dao.getAll();
request.setAttribute("teaList", teaList);
request.setAttribute("date", new Date());
//這個頁面跳轉會把request中的值帶過去,區別於重定向,位址列顯示不發生改變
//跳轉到jsp頁面的時候寫反斜號
request.getRequestDispatcher("/list.jsp").forward(request, response);
}
}
---------------------------------------程式碼結束-------------------------------------------
TeacherTest.java
---------------------------------------程式碼開始-------------------------------------------
package com.test;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.dao.TeacherDAO;
import com.dao.impl.TeacherDAOImpl;
import com.entity.Teacher;
public class TeacherTest {
@Test
public void getALLTest(){
TeacherDAO dao=new TeacherDAOImpl();
List<Teacher> teaList=dao.getAll();
for(Teacher t:teaList){
System.out.println(t);
}
}
@Test
public void addTest(){
TeacherDAO dao=new TeacherDAOImpl();
Teacher tea=new Teacher();
tea.setTeaName("梁山伯");
tea.setTeaAge(15);
tea.setGrade(3);
Assert.assertSame(1, dao.add(tea));
}
}
---------------------------------------程式碼結束-------------------------------------------
log4j.properties
---------------------------------------程式碼開始-------------------------------------------
#appender是輸出源,stdout是自定義的名字,target是輸出目標,ConsoleAppender是輸出到控制檯
#layout是輸出佈局,PatternLayout是模芯佈局,ConversionPattern是格式轉換,FileAppender是
#輸出到檔案
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} %m %l %n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=E:\test.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} %m %l %n
log4j.rootLogger=error, stdout
#%p是輸出優先順序debug,info,warn,error,fatal 設定為warn時就只能顯示warn,error,fatal
#%d是日期格式
#%m是錯誤資訊
#%l是錯誤所在類
#%n是錯誤位置
#空格依然是空格
---------------------------------------程式碼結束-------------------------------------------
mybaits-config.xml
---------------------------------------程式碼開始-------------------------------------------
<?xml version="1.0" encoding="UTF-8" ?>
<!-- dtd字尾檔案是標籤資訊驗證,沒有它就不會有標籤提示, 並且無法使用這些標籤,是xml檔案的一部分 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<!-- 類型別名,給com.entity包下的所有實體類起別名,別名就是類名,且不分大小寫 ,用在mapper對映檔案中-->
<package name="com.entity" />
</typeAliases>
<environments default="development">
<!-- 用連線池載入資料庫的資料 -->
<environment id="development">
<transactionManager type="JDBC" /> <!-- 交易管理型別 -->
<dataSource type="POOLED">
<!-- 我在這裡遇到一個問題,後面執行程式碼的時候,顯示錯誤no suit driver,後來發現是因為driver和url的值裡面有一個小小的空格,去掉就好了 -->
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/school?"/>
<property name="username" value="root" />
<property name="password" value="abcd1234" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 這裡載入的必須是有內容的mapper對映檔案,否則會報錯而且你死也找不到,我已經死過一回了 -->
<mapper resource="com/mapper/TeacherMapper.xml" />
</mappers>
</configuration>
---------------------------------------程式碼結束-------------------------------------------
add.jsp
---------------------------------------程式碼開始-------------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<!-- input的型別選擇是實現不同功能的前提 -->
<form action="addTeacherServlet" method="post">
姓名<input type="text" name="name" value=""/><br/>
年齡<input type="text" name="age" value=""/><br/>
年級<input type="text" name="grade" value=""/><br/>
<br/>
<input type="submit" value="提交">
</form>
---------------------------------------程式碼結束-------------------------------------------
list.jsp
---------------------------------------程式碼開始-------------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<!-- prefix是自定義的 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<a href="add.jsp">新增</a>
<table border="1">
<tr>
<td>學生序號</td>
<td>學生學號</td>
<td>學生姓名</td>
<td>學生年齡</td>
<td>學生年級</td>
</tr>
<!--
items英語是專案的意思,在這裡接受跳轉頁面的資料,var是臨時變數,用來迴圈遍歷,varStatus是迴圈序號,count相當於一個顯示序號的方法
jsp頁面用錢號$獲得傳來的值,mapper中用得是#
-->
<c:forEach items="${teaList}" var="tea" varStatus="v">
<tr>
<td>${v.count}</td>
<td>${tea.teaId}</td>
<td>${tea.teaName}</td>
<td>${tea.teaAge}</td>
<td>${tea.gradeId}</td>
</tr>
</c:forEach>
<!-- 日期格式:YYYY-MM-DD HH:mm:ss:SS 表示 :年份-月份-日 時:分:秒:毫秒 -->
<td colspan="5" align="center"><fmt:formatDate value="${date}" pattern="YYYY-MM-DD HH:mm:ss:SS"/></td>
</table>
---------------------------------------程式碼結束-------------------------------------------
至此,專案完成