程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java+MyBatis+MySQL開辟情況搭建流程詳解

Java+MyBatis+MySQL開辟情況搭建流程詳解

編輯:關於JAVA

Java+MyBatis+MySQL開辟情況搭建流程詳解。本站提示廣大學習愛好者:(Java+MyBatis+MySQL開辟情況搭建流程詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Java+MyBatis+MySQL開辟情況搭建流程詳解正文


重要搭建進程

1. pom.xml文件中參加mybatis和數據庫依附,這裡應用mysql:

<properties> 
 <mybatis.version>3.2.3</mybatis.version> 
 <mysql.version>5.1.26</mysql.version> 
 <slf4j.api.version>1.7.5</slf4j.api.version> 
 <testng.version>6.8.7</testng.version> 
</properties> 
 
<dependencies> 
 <dependency> 
  <groupId>org.mybatis</groupId> 
  <artifactId>mybatis</artifactId> 
  <version>${mybatis.version}</version> 
 </dependency> 
 <!-- Database driver --> 
 <dependency> 
  <groupId>mysql</groupId> 
  <artifactId>mysql-connector-java</artifactId> 
  <version>${mysql.version}</version> 
 </dependency> 
 <!-- mybatis啟動要加載log4j --> 
 <dependency> 
  <groupId>org.slf4j</groupId> 
  <artifactId>slf4j-log4j12</artifactId> 
  <version>${slf4j.api.version}</version> 
 </dependency> 
 <!-- Test --> 
 <dependency> 
  <groupId>org.testng</groupId> 
  <artifactId>testng</artifactId> 
  <version>${testng.version}</version> 
 </dependency> 
</dependencies> 


2. 在類途徑下創立mybatis的設置裝備擺設文件Configuration.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.john.hbatis.model.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://localhost:3306/hbatis" /> 
      <property name="username" value="root" /> 
      <property name="password" value="123456" /> 
    </dataSource> 
   </environment> 
  </environments> 
   
  <mappers><!-- ORM映照文件 --> 
    <mapper resource="com/john/hbatis/model/User.xml" /> 
  </mappers> 
 </configuration> 


3. 履行創立數據庫和表的sql:

-- Create the database named 'hbatis'. 
-- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible. 
CREATE DATABASE IF NOT EXISTS `hbatis` 
DEFAULT CHARACTER SET = `UTF8`; 
 
-- Create a table named 'User' 
CREATE TABLE `user` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `name` varchar(50) DEFAULT NULL, 
  `age` int(11) DEFAULT NULL, 
  `address` varchar(200) DEFAULT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 
 
-- Insert a test record 
Insert INTO `user` VALUES ('1', 'john', '120', 'hangzhou,westlake'); 


4. com.john.hbatis.model.User類:

public class User { 
  private int id; 
  private String name; 
  private String age; 
  private String address; 
  // Getters and setters are omitted 
 
  // 假如有帶參數的結構器,編譯器不會主動生成無參結構器。當查詢須要前往對象時,ORM框架用反射來挪用對象的無參結構函數,招致異常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.<init>() 
  // 這時候須要明白寫出: 
  public User() { 
  } 
 
  public User(int id, String address) { 
    this.id = id; 
    this.address = address; 
  } 
 
  public User(String name, int age, String address) { 
    this.name = name; 
    this.age = age; 
    this.address = address; 
  } 
} 

com/john/hbatis/model途徑下的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.john.hbatis.model.UserMapper"> 
  <select id="getUserById" parameterType="int" resultType="User"> 
    select * from `user` where id = #{id} 
  </select> 
</mapper> 


5. 測試類:

public class MyBatisBasicTest { 
  private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class); 
  private static SqlSessionFactory sqlSessionFactory; 
   
  private static Reader reader; 
   
  @BeforeClass 
  public static void initial() { 
    try { 
      reader = Resources.getResourceAsReader("Configuration.xml"); 
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 
    } catch (IOException e) { 
      log.error("Error thrown while reading the configuration: {}", e); 
    } finally { 
      if (reader != null) { 
        try { 
          reader.close(); 
        } catch (IOException e) { 
          log.error("Error thrown while closing the reader: {}", e); 
        } 
      } 
    } 
  } 
   
  @Test 
  public void queryTest() { 
    SqlSession session = sqlSessionFactory.openSession(); 
    User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1); 
    log.info("{}: {}", user.getName(), user.getAddress()); 
  } 
} 

以接口方法交互數據
下面的情況搭建是采取SqlSession的通用辦法並強迫轉換的方法,存在著轉換平安的成績:

User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1); 

可以采取接口加sql語句的方法來處理,sql語句懂得為是接口的完成:

1. 新建接口類:

package com.john.hbatis.mapper; 
 
import com.john.hbatis.model.User; 
 
public interface IUserMapper { 
  User getUserById(int id); 
} 

2. 修正User.xml文件,確保namespace屬性值和接口的全限制名雷同,且id屬性值和接口辦法名雷同:

<mapper namespace="com.john.hbatis.mapper.IUserMapper"> 
  <select id="getUserById" 

3. 在MyBatisBasicTest類中添加測試辦法:

@Test 
public void queryInInterfaceWayTest() { 
  SqlSession session = sqlSessionFactory.openSession(); 
  IUserMapper mapper = session.getMapper(IUserMapper.class); // 假如namespace和接口全限制名紛歧致,報org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry異常。 
  User user = mapper.getUserById(1); 
  log.info("{}: {}", user.getName(), user.getAddress()); 
} 

附:
下面的完成是把sql語句放在XML文件中,並經由過程必定的束縛來包管接口可以或許在XML中找到對應的SQL語句;
還有一種方法是經由過程接口+注解SQL方法來交互數據:

1. 新建接口類:

package com.john.hbatis.mapper; 
 
import org.apache.ibatis.annotations.Select; 
 
import com.john.hbatis.model.User; 
 
public interface IUserMapper2 { 
  @Select({ "select * from `user` where id = #{id}" }) 
  User getUserById(int id); 
} 

2. 在Configuration.xml文件中參加:

<mappers> 
  <mapper class="com.john.hbatis.mapper.IUserMapper2" /> 
</mappers> 

或在初始化語句中參加:

sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class); 

3. 響應修正下面的測試辦法:

IUserMapper2 mapper = session.getMapper(IUserMapper2.class); 

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