程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java的MyBatis框架項目搭建與hellow world示例

Java的MyBatis框架項目搭建與hellow world示例

編輯:關於JAVA

Java的MyBatis框架項目搭建與hellow world示例。本站提示廣大學習愛好者:(Java的MyBatis框架項目搭建與hellow world示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java的MyBatis框架項目搭建與hellow world示例正文


新建項目(我應用的是maven項目)mybatis-study-01

1、參加mybatis與mysql-connector依附包到pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>mybatis</groupId>
 <artifactId>mybatis-study-01</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>mybatis-01</name>
 <url>http://maven.apache.org</url>

 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties> 

 <dependencies>
 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.10</version>
  <scope>test</scope>
 </dependency>
 
 <dependency>
 <groupId>org.mybatis</groupId>
 <artifactId>mybatis</artifactId>
 <version>3.2.3</version>
 </dependency>
 
 <dependency> 
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.27</version>
 </dependency>
   
  
 </dependencies>
</project>

2、創立數據庫mybatis-test
新建一張user表用於測試。建表sql以下:

CREATE TABLE `user` (
 `id` int(11) NOT NULL auto_increment,
 `password` varchar(255) default NULL,
 `user_name` varchar(50) default NULL,
 `user_age` int(11) default NULL,
 `user_address` varchar(200) default NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `userName` (`user_name`)
) EN

拔出一條數據

INSERT INTO `user` VALUES ('1', '123131', 'summer', '100', 'shanghai,pudong');


3、在項目中編寫pojo對象。

package com.zf.mybatis.pojo;

public class User {

 private int id;
 private String password ;
 private String userName;
 private String userAge;
 private String userAddress;

 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getUserName() {
 return userName;
 }
 public void setUserName(String userName) {
 this.userName = userName;
 }
 public String getUserAge() {
 return userAge;
 }
 public void setUserAge(String userAge) {
 this.userAge = userAge;
 }
 public String getUserAddress() {
 return userAddress;
 }
 public void setUserAddress(String userAddress) {
 this.userAddress = userAddress;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }

}

4、編寫pojo對應的映照文件User.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.zf.mybatis.pojo.UserMapper">

 <!-- 應用sql標簽可以將公共的sql提掏出來復用 -->
 <sql id="queryFields">
 id , password , user_name as userName , user_age as userAge , user_address as userAddress
 </sql>
 
 <select id="selectByID" parameterType="int" resultType="User">
  select 
  <include refid="queryFields"/> 
  from `user` where id = #{id}
 </select>
 
 <insert id="add" parameterType="User" useGeneratedKeys="true" keyProperty="id" >
  insert into `user`
  (password , user_name , user_age , user_address)
  values(#{password} , #{userName} , #{userAge} , #{userAddress} )
 </insert>
 
 <update id="update" parameterType="User" >
 update `user`
 set password = #{password} , user_name = #{userName}, user_age = #{userAge}, user_address = #{userAddress}
 where id = #{id}
 </update>
 
 <delete id="deleteById" parameterType="int">
  delete from `user` where id = #{id}
 </delete>
 
 
</mapper>

留意:下面的namespace的值為com.zf.mybatis.pojo.UserMapper,可以自界說 ,UserMapper不是一個類,不須要存在的。
別的,mybatis會將從數據庫查詢出來的記載依據列名與pojo中的字段停止婚配, 所以下面的user_name,user_age ,user_address這幾個字段都取了別號,跟pojo中的字段絕對應。 假如不起別號, 查詢出來的對象,這幾個字段是沒有值的。


5、編寫mybatis的設置裝備擺設文件mybatis-config.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>

 <!-- 設置裝備擺設別號 -->
 <typeAliases> 
  <typeAlias alias="User" type="com.zf.mybatis.pojo.User"/> 
 </typeAliases> 

 <!-- 數據庫設置裝備擺設信息 -->
 <environments default="development">
 <environment id="development">
  <transactionManager type="JDBC"/>
  <dataSource type="POOLED">
  <property name="driver" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis-test"/>
  <property name="username" value="root"/>
  <property name="password" value="root"/>
  </dataSource>
 </environment>
 </environments>
 
 <!-- 映照文件 -->
 <mappers>
 <mapper resource="conf/User.xml"/>
 </mappers>
</configuration>

在該設置裝備擺設文件中設置裝備擺設了數據庫的鏈接方法,和注冊一切的映照文件,還可以設置mybatis的一些參數。

如今便可以編寫測試類了。來測試一下。

package com.zf.mybatis;

import java.io.IOException;
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;
import org.junit.Before;
import org.junit.Test;

import com.zf.mybatis.pojo.User;

public class TestMyBatis {
 
 private SqlSessionFactory sqlSessionFactory;
 private Reader reader; 

 @Before
 public void init(){
 try {
 reader = Resources.getResourceAsReader("mybatis-config.xml");
 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 
 @Test
 public void testQueryUser(){
 SqlSession session = sqlSessionFactory.openSession();
 try {
 User user = (User) session.selectOne("com.zf.mybatis.pojo.UserMapper.selectByID" ,1);
 System.out.println(user.getUserAddress());
 System.out.println(user.getUserName());
 } finally {
 session.close();
 }
 }
 
 @Test
 public void testInsertUser(){
 SqlSession session = sqlSessionFactory.openSession();
 try {
 User user = new User() ;
 user.setUserName("abcde");
 user.setUserAge(15) ;
 user.setUserAddress("hangzhou/zhejiang");
 user.setPassword("123456");
 //前往值是記載條數
 int resultCount = session.insert("com.zf.mybatis.pojo.UserMapper.add", user );
 session.commit() ;
 System.out.printf("userID:%d,總記載條數:%d" , user.getId() , resultCount); //獲得拔出對象的id
 } finally {
 session.close();
 }
 }
 
 @Test
 public void testUpdateUser(){
 SqlSession session = sqlSessionFactory.openSession();
 try {
 User user = new User() ;
 user.setId(5) ;
 user.setUserName("updateName");
 user.setUserAge(101) ;
 user.setUserAddress("shenzhen/guangdong");
 user.setPassword("000000");
 //前往值是修正條數
 int updateCount = session.update("com.zf.mybatis.pojo.UserMapper.update", user );
 session.commit() ;
 System.out.printf("修正條數:%d" ,updateCount); 
 } finally {
 session.close();
 }
 }
 
 @Test
 public void testDelete(){
 SqlSession session = sqlSessionFactory.openSession();
 try {
 //前往值是刪除條數
 int deleteCount = session.update("com.zf.mybatis.pojo.UserMapper.deleteById", 4 );
 session.commit() ;
 System.out.printf("刪除條數:%d" ,deleteCount ); 
 } finally {
 session.close();
 }
 }


}

運轉testQueryUser成果以下:

shanghai,pudong
summer

到此,一個mybatis的helloworld類型的小法式就出來了。

PS:MyBaits設置裝備擺設文件報錯處理
Mybaits的設置裝備擺設文件校驗很詭異,節點的地位還有請求
以下,會報錯:

The content of element type "configuration" must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,mappers?)". 

<?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> 
 
  
 <environments default="development"> 
  <environment id="development"> 
   <transactionManager type="JDBC"/> 
   <dataSource type="POOLED"> 
    <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 
    <property name="url" value="jdbc:oracle:thin:@xx:1521:xx"/> 
    <property name="username" value="ireport"/> 
    <property name="password" value="xxxx"/> 
   </dataSource> 
  </environment> 
 </environments> 
  
 <typeAliases> 
  <typeAlias type="com.ice.stat.online.model.EventFlag" alias="EventFlag"/> 
 </typeAliases> 
  
 <mappers> 
  <mapper resource="com/ice/stat/online/model/hbm/EventFlagMapper.xml"/> 
 </mappers> 
  
</configuration> 

 
把typeAliases放到最下面就行了說:

<?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> 
 <typeAliases> 
  <typeAlias type="com.ice.stat.online.model.EventFlag" alias="EventFlag"/> 
 </typeAliases> 
  
 <environments default="development"> 
  <environment id="development"> 
   <transactionManager type="JDBC"/> 
   <dataSource type="POOLED"> 
    <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 
    <property name="url" value="jdbc:oracle:thin:@xx:1521:xx"/> 
    <property name="username" value="ireport"/> 
    <property name="password" value="xxxx"/> 
   </dataSource> 
  </environment> 
 </environments> 
  
  
 <mappers> 
  <mapper resource="com/ice/stat/online/model/hbm/EventFlagMapper.xml"/> 
 </mappers> 
  
</configuration> 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved