设为首页 收藏本站
查看: 644|回复: 0

[经验分享] myBatis系列之一:搭建开发环境

[复制链接]
发表于 2016-11-25 07:12:30 | 显示全部楼层 |阅读模式
myBatis系列之二:以接口方式交互数据
myBatis系列之三:增删改查
myBatis系列之四:关联数据的查询
myBatis系列之五:与Spring3集成
myBatis系列之六:与SpringMVC集成
myBatis系列之七:事务管理

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


参考:
http://www.yihaomen.com/article/java/303.htm

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305086-1-1.html 上篇帖子: MyBatis入门实例简介 下篇帖子: spring与mybatis三种整合方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表