1. 程式人生 > >java專案單獨使用mybatis的小例子

java專案單獨使用mybatis的小例子

朋友讓我幫他寫幾個介面,因為比較簡單,使用jdbc程式設計,後來發現數據庫欄位和實體類中物件屬性不能實現對映,我使用mybatis框架。我使用httpClient的post方式來測試介面,專案所需包如下:


目錄結構:


在src建立資料庫配置檔案mysql.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456


建立實體物件Goods

package pojo;
import java.math.BigDecimal;
public class Goods {
	private String goodCode;
	private String barCode;
	private String nsUrl;
	private String categoryTitle;
	private String title;
	private String remark;
	private Integer reserve;
	private Integer packge;
	private BigDecimal price;
	private String dicount;
	private BigDecimal discountPrice;
	private Integer carCount;
	public String getGoodCode() {
		return goodCode;
	}
	public void setGoodCode(String goodCode) {
		this.goodCode = goodCode;
	}
	public String getBarCode() {
		return barCode;
	}
	public void setBarCode(String barCode) {
		this.barCode = barCode;
	}
	public String getNsUrl() {
		return nsUrl;
	}
	public void setNsUrl(String nsUrl) {
		this.nsUrl = nsUrl;
	}
	public String getCategoryTitle() {
		return categoryTitle;
	}
	public void setCategoryTitle(String categoryTitle) {
		this.categoryTitle = categoryTitle;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public Integer getReserve() {
		return reserve;
	}
	public void setReserve(Integer reserve) {
		this.reserve = reserve;
	}
	public Integer getPackge() {
		return packge;
	}
	public void setPackge(Integer packge) {
		this.packge = packge;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
	public String getDicount() {
		return dicount;
	}
	public void setDicount(String dicount) {
		this.dicount = dicount;
	}
	public BigDecimal getDiscountPrice() {
		return discountPrice;
	}
	public void setDiscountPrice(BigDecimal discountPrice) {
		this.discountPrice = discountPrice;
	}
	public Integer getCarCount() {
		return carCount;
	}
	public void setCarCount(Integer carCount) {
		this.carCount = carCount;
	}
	
}


建立GoodsMapper.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.GoodsMapper">
	<!-- 自定義返回結果集 -->
	<resultMap id="goodsMap" type="Goods">
		<id property="goodCode" column="goodCode" javaType="java.lang.String"></id>
		<result property="barCode" column="barCode" javaType="java.lang.String"></result>
		<result property="nsUrl" column="nsUrl" javaType="java.lang.String"></result>
		<result property="categoryTitle" column="categoryTitle" javaType="java.lang.String"></result>
		<result property="title" column="title" javaType="java.lang.String"></result>
		<result property="remark" column="remark" javaType="java.lang.String"></result>
		<result property="reserve" column="reserve" javaType="java.lang.Integer"></result>
		<result property="packge" column="packge" javaType="java.lang.Integer"></result>
		<result property="price" column="price" javaType="java.math.BigDecimal"></result>
		<result property="dicount" column="dicount" javaType="java.lang.String"></result>
		<result property="discountPrice" column="discountPrice" javaType="java.math.BigDecimal"></result>
		<result property="carCount" column="carCount" javaType="java.lang.Integer"></result>
	</resultMap>
	<select id="selectAllGoods" resultMap="goodsMap">
		select * from goods
	</select>
	
	<select id="selectRecommendGoods" resultMap="goodsMap">
		select * from goods limit 0,4;
	</select>
</mapper>  

建立介面GoodsMapper.java

package mapper;
import java.util.List;
import pojo.Goods;

public interface GoodsMapper {
	public List<Goods> selectAllGoods() throws Exception;
	public List<Goods> selectRecommendGoods() throws Exception;
}

mybatis.cfg.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>
    <!-- 引入外部配置檔案 -->
    <properties resource="mysql.properties"></properties>
     <!-- 為JAVA Bean起類別名 -->
    <typeAliases >
         <!-- 別名方式1,一個一個的配置 type中放置的是類的全路徑,alias中放置的是類別名
         <typeAliase type="com.cy.mybatis.beans.UserBean" alias="UserBean"/>-->
         <!-- 別名方式2,自動掃描,將JAVA類的類名作為類的類別名 -->
         <package name="pojo"/>
    </typeAliases>
   
     <!-- 配置mybatis執行環境 -->
       <environments default="cybatis">
         <environment id="cybatis">
             <!-- type="JDBC" 代表使用JDBC的提交和回滾來管理事務 -->
             <transactionManager type="JDBC" />
             <!-- mybatis提供了3種資料來源型別,分別是:POOLED,UNPOOLED,JNDI -->
             <!-- POOLED 表示支援JDBC資料來源連線池 -->
             <!-- UNPOOLED 表示不支援資料來源連線池 -->
             <!-- JNDI 表示支援外部資料來源連線池 -->
             <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>
         <!-- 告知對映檔案方式1,一個一個的配置
         <mapper resource="com/cy/mybatis/mapper/UserMapper.xml"/>-->
         <!-- 告知對映檔案方式2,自動掃描包內的Mapper介面與配置檔案 -->
         <package name="mapper"/>
     </mappers>
</configuration>


資料庫連線工具類DBTools

package until;
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();
}
}

selectGoods.java 程式碼(servlet介面)

package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 org.apache.ibatis.session.SqlSession;
import mapper.GoodsMapper;
import net.sf.json.JSONArray;
import pojo.Goods;
import until.DBTools;


/**
 * Servlet implementation class TestSvrvlet
 */
@WebServlet("/getAllGoods")
public class selectGoods extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
try {
out.println(selectAllGoods());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
try {
out.println(selectAllGoods());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 整合mybatis後查詢商品方法
* 
* @return
*/
private String selectAllGoods() {
JSONArray jr = new JSONArray();
SqlSession session = DBTools.getSession();
GoodsMapper mapper = session.getMapper(GoodsMapper.class);
try {
List<Goods> goodsList = mapper.selectAllGoods();
System.out.println(goodsList.toString());
jr = JSONArray.fromObject(goodsList);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
System.out.println("jr" + jr);
return jr.toString();
}
}

TestHttpClient.java

package test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class TestHttpClient {
public void postGoods() {
// 建立預設的httpClient例項.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立httppost
HttpPost httppost = new HttpPost("http://localhost:8080/test/getAllGoods");
UrlEncodedFormEntity uefEntity = null;
try {
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連線,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

//測試方法
public static void main(String[] args) {
TestHttpClient httpte = new TestHttpClient();
httpte.postGoods();
}
}


控制檯輸出內容

--------------------------------------
Response content: [{"carCount":0,"dicount":"","categoryTitle":"","remark":"很好","goodCode":"10000","packge":0,"discountPrice":0,"title":"筆記本","price":3000,"nsUrl":"","barCode":"1111","reserve":0},{"carCount":0,"dicount":"","categoryTitle":"","remark":"一般","goodCode":"10001","packge":0,"discountPrice":0,"title":"杯子","price":2500,"nsUrl":"","barCode":"4444","reserve":0},{"carCount":0,"dicount":"","categoryTitle":"","remark":"還可以","goodCode":"10002","packge":0,"discountPrice":0,"title":"水壺","price":20,"nsUrl":"","barCode":"2222","reserve":0},{"carCount":0,"dicount":"","categoryTitle":"","remark":"不錯","goodCode":"10003","packge":0,"discountPrice":0,"title":"雨傘","price":30,"nsUrl":"","barCode":"3333","reserve":0},{"carCount":0,"dicount":"","categoryTitle":"","remark":"質量上好","goodCode":"10004","packge":0,"discountPrice":0,"title":"紙巾","price":5,"nsUrl":"","barCode":"5555","reserve":0},{"carCount":0,"dicount":"","categoryTitle":"","remark":"垃圾","goodCode":"10005","packge":0,"discountPrice":0,"title":"手機","price":3000,"nsUrl":"","barCode":"6666","reserve":0}]


--------------------------------------


資料庫,goods表


測試成功,整個流程跑通