1 项目说明

项目采用 maven 组织 ,依赖 mysql-connector-java,org.mybatis,junit pom 依赖如下:

mysql 数据连接 :

mysql-connector-java

mybatis

mybatis

junit

junit 单元测试,本项目采用junit 跑单元测试,4.12 版本采用 @Test注解 测试方法,3.X 版本采用继承来实现测试方法

<dependencies>

<!-- https://mvnrepository.com/artifact/junit/junit -->

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.4.5</version>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.30</version>

</dependency>

</dependencies>

2 项目结构

3 DB 脚本

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(45) DEFAULT NULL,

`money` decimal(10,0) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;

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

-- Records of account

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

INSERT INTO `account` VALUES ('', 'hbb0b0', '');

INSERT INTO `account` VALUES ('', 'kael', '');

4 代码说明

MyDataSourceFactory

package hbb0b0.JavaBasic.mybatis03;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceFactory;

import org.apache.ibatis.datasource.pooled.PooledDataSource;

public class MyDataSourceFactory implements DataSourceFactory {

private Properties prop;

public DataSource getDataSource() {

PooledDataSource ds = new PooledDataSource();

ds.setDriver(prop.getProperty("driver"));

ds.setUrl(prop.getProperty("url"));

ds.setUsername(prop.getProperty("user"));

ds.setPassword(prop.getProperty("password"));

return ds;

}

public void setProperties(Properties prprts) {

prop = prprts;

}

}
  • model
package hbb0b0.JavaBasic.model;

import java.io.Serializable;

public class Account implements Serializable{

private int id;

private String name;

private double money;

public Account() {

super();

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getMoney() {

return money;

}

public void setMoney(double money) {

this.money = money;

}

@Override

public String toString() {

return "Account [id=" + id + ", name=" + name + ", money=" + money

+ "]";

}

}
  • mapper interface
package hbb0b0.JavaBasic.mybatis03;

import org.apache.ibatis.annotations.Select;

public interface AccountMapper {

@Select("SELECT * FROM Account WHERE id = #{id}")

Account getAccountById(int id);

}
  • session简单封装
package hbb0b0.JavaBasic.mybatis03;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;

import org.apache.ibatis.session.Configuration;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.apache.ibatis.transaction.TransactionFactory;

import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class DbTool {

private static SqlSessionFactory m_sessionFactory;

private static void initSessionFactory()

{

Properties prop = new Properties();

prop.setProperty("driver", "com.mysql.jdbc.Driver");

prop.setProperty("url", "jdbc:mysql://localhost:3306/Study");

prop.setProperty("user", "root");

prop.setProperty("password", "sqlsa");

MyDataSourceFactory mdsf = new MyDataSourceFactory();

mdsf.setProperties(prop);

DataSource ds = mdsf.getDataSource();

TransactionFactory trFact = new JdbcTransactionFactory();

Environment environment = new Environment("development", trFact, ds);

Configuration config = new Configuration(environment);

config.addMapper(AccountMapper.class);

m_sessionFactory = new SqlSessionFactoryBuilder().build(config);

}

public static SqlSessionFactory GetSqlSessionFactory()

{

if(m_sessionFactory==null)

{

initSessionFactory();

}

return m_sessionFactory;

}

}
  • JUNit
package hbb0b0.JavaBasic.mybatis03;

import static org.junit.Assert.assertNotNull;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import org.junit.Assert;

import org.junit.Test;

import java.lang.System;

/**

* Unit test for simple App.

*/

public class AppTest

{

@Test

public void getOne_Test() throws IOException {

SqlSession session = DbTool.GetSqlSessionFactory().openSession();

try {

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

assertNotNull(mapper);

Account account = mapper.getAccountById(1);

assertNotNull(account);

Assert.assertEquals("hbb0b0",account.getName());

System.out.println(account.toString());

} finally {

session.close();

}

}

}

测试结果:

Java DB 访问(三)mybatis mapper interface接口的更多相关文章

  1. Java DB 访问之 mybatis mapper xml 配置方式

    1 项目说明 项目采用 maven 组织 ,jdbc 唯一的依赖就是 mysql-connector-java pom 依赖如下: mysql 数据连接 : mysql-connector-java ...

  2. springboot访问出错,mapperScan导包错误java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.<init>() at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_172] at java.

    2019-08-06 12:42:03.153 ERROR 10080 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Se ...

  3. java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.SpecialProvider.<init>()

    Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis ...

  4. Cause: java. lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseInsertProvider

    相信现在Java Web开发都是用的mybatis吧,而用到mybatis很多人都不会错过通用mapper吧! (纯属瞎扯淡...qwq). 如我上一篇博客所写,目前公司新项目,使用了通用mapper ...

  5. 解决java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    今天在集成Mapper时 出现如下错误 java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvi ...

  6. Java DB 访问之(四) spring mvc 组合mybatis

    说明 本项目采用 maven 结构,主要演示了 spring mvc + mybatis,controller 获取数据后以json 格式返回数据. 项目结构 包依赖 与说明 pom文件: <p ...

  7. JAVA 构造器, extends[继承], implements[实现], Interface[接口], reflect[反射], clone[克隆], final, static, abstrac

    记录一下: 构造器[构造函数]: 在java中如果用户编写类的时候没有提供构造函数,那么编译器会自动提供一个默认构造函数.它会把所有的实例字段设置为默认值:所有的数字变量初始化为0;所有的布尔变量设置 ...

  8. Java知多少(39)interface接口

    在抽象类中,可以包含一个或多个抽象方法:但在接口(interface)中,所有的方法必须都是抽象的,不能有方法体,它比抽象类更加“抽象”. 接口使用 interface 关键字来声明,可以看做是一种特 ...

  9. Java DB访问之 JDBC

    项目说明 项目采用 maven 组织 ,jdbc 唯一的依赖就是 mysql-connector-java pom 依赖如下: <dependency> <groupId>my ...

随机推荐

  1. Vue自定义指令报错:Failed to resolve directive: xxx

    Vue自定义指令报错 Failed to resolve directive: modle 这个报错有2个原因: 1.指令单词拼错 2.Vue.directive() 这个方法没有写在 new Vue ...

  2. Codeforces Round #519 by Botan Investments F. Make It One

    https://codeforces.com/contest/1043/problem/F 题意 给你n个数,求一个最小集合,这个集合里面数的最大公因数等于1 1<=n<=3e5 1< ...

  3. vetur插件提示 [vue-language-server] Elements in iteration expect to have 'v-bind:key' directives

    错误如下图所示: 错误提示: [vue-language-server] Elements in iteration expect to have 'v-bind:key' directives.Re ...

  4. mysql的myBatis,主键自增设置

    方法一: insert id="insert" parameterType="Person" useGeneratedKeys="true" ...

  5. 添加wifi adb

    https://blog.csdn.net/ouyang_peng/article/details/50370786 首先弄懂怎么设置adb wifi无线调试的功能,如下所示. 1. 手机端开启adb ...

  6. BAT文件语法和技巧(bat文件的编写及使用)

    源文链接:http://www.jb51.net/article/5828.htm 比较有用的东比较有用的东西 首先,批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们 ...

  7. WordPaster2产品介绍

    更新WordParser组件,集成ImagePaster组件功能.完善粘贴剪帖板图片,粘贴电脑图片文件,粘贴word,粘贴excel逻辑. 大幅度优化和精简js代码,js代码行数从1932行减少到97 ...

  8. day27(反射之内省机制实现BeanUtils)

    使用内省方式来实现beanUtils往对象里面存值 public class BeanInfoUtil2 { public static void setPropertyByIntrospector( ...

  9. Codeforces Round #264 (Div. 2) D. Gargari and Permutations 多序列LIS+dp好题

    http://codeforces.com/contest/463/problem/D 求k个序列的最长公共子序列. k<=5 肯定 不能直接LCS 网上题解全是图论解法...我就来个dp的解法 ...

  10. [kuangbin]树链剖分 D - 染色

    https://vjudge.net/contest/251031#problem/Dhttps://blog.csdn.net/kirito_acmer/article/details/512019 ...