欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java+MyBatis+MySQL开发环境搭建流程详解

程序员文章站 2024-03-11 23:08:31
主要搭建过程 1. pom.xml文件中加入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);