MyBatisPartA
(正在补充)
1.从第一个程序开始,通过mybatis实现数据库表内容的增删改查
1.0准备工作
建数据库mybatis,在其中创建表sql语句如下:
SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL COMMENT '下单用户id',
`number` VARCHAR(32) NOT NULL COMMENT '订单号',
`createtime` DATETIME NOT NULL COMMENT '创建订单时间',
`note` VARCHAR(100) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('', '', '', '2015-02-04 13:22:35', NULL);
INSERT INTO `orders` VALUES ('', '', '', '2015-02-03 13:22:41', NULL);
INSERT INTO `orders` VALUES ('', '', '', '2015-02-12 16:13:23', NULL); -- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(32) NOT NULL COMMENT '用户名称',
`birthday` DATE DEFAULT NULL COMMENT '生日',
`sex` CHAR(1) DEFAULT NULL COMMENT '性别',
`address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('', '王五', NULL, '', NULL);
INSERT INTO `user` VALUES ('', '张三', '2014-07-10', '', '北京市');
INSERT INTO `user` VALUES ('', '张小明', NULL, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', NULL, '', '河南郑州');
INSERT INTO `user` VALUES ('', '张三丰', NULL, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', NULL, '', '河南郑州');
INSERT INTO `user` VALUES ('', '王五', NULL, NULL, NULL);
1.1新建java项目(mytatis-a1)
创建lib文件夹,加入mybaties核心包、依赖包、数据库包(整合包点我下载),build to path
创建config资源文件,放置配置文件
config/创建sqlMapConfig.xml(核心配置文件)
config/创建log4j.properties(日志)
config/创建sqlmap/user.xml(写sql语句)
创建包com.mybatis.pojo/下根据数据库表创建User.java
com.mybatis.test/MybatiesTest.java
结构图如下:
填写代码:
sqlMapConfig.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>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/user.xml"/>
</mappers> </configuration>
log4j.properites
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="test">
<select id="queryUserById" parameterType="Integer" resultType="com.mybaties.pojo.User">
select * from user where id = #{v}
</select>
</mapper>
User.java
package com.mybaties.pojo; import java.io.Serializable;
import java.util.Date; public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址 public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
} }
MybatisTest.java
package com.mybaties.test; import java.io.InputStream; 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; public class MybatiesTest {
private SqlSessionFactory factory; @Before
public void init() throws Exception{
InputStream in =
Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
this.factory = builder.build(in);
} @Test
public void testQueryUserById(){
SqlSession session = factory.openSession();
Object user = session.selectOne("test.queryUserById", 37);
System.out.println(user); }
}
MybatiesTest.java
package com.mybaties.test; import java.io.IOException;
import java.io.InputStream; 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.Test; public class MybatiesTest1 { @Test
public void testQueryUserById() throws IOException{
InputStream in =
Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
Object user = session.selectOne("test.queryUserById", 37);
System.out.println(user); }
}
junit:MybatiesTest中testQueryUserById结果如图:
MyBatisPartA的更多相关文章
随机推荐
- hdu 2528:Area(计算几何,求线段与直线交点 + 求多边形面积)
Area Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- hdu 1174:爆头(计算几何,三维叉积求点到线的距离)
爆头 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submissi ...
- iOS开发之--FMDB的使用
在很多时候,我们会用到数据库,我们移动端使用的数据库,一般都是嵌入型数据库,是一种较轻型的数据库, 一般很多时候,大牛封装的FMDB的第三方,已经足够满足我们的需求了! 现在分享一下自己的学习心得,希 ...
- wap开发体会<转载>
前二天因工作需要,上头要求做一个wap版的网站,到网上学习了一天,弄了个beta版出来(http://wap.luckty.com 功能很一般),整理几点经验如下: 1.wap网站用的是wml标识,非 ...
- Swift 实现单例模式Singleton pattern的三种方法
转自:点击打开链接 From my short experience with Swift there are three approaches to implement the Singleton ...
- mysql如何用sql添加字段如何设置字符集和排序规则
alter table pay_company add sms_code2 varchar(16) CHARACTER SET UTF8 COLLATE utf8_general_ci DEFAULT ...
- 修改Linux的基本配置(如主机名、ip等)
1.修改主机名 vi /etc/sysconfig/network 2.修改ip地址(注意修改完了后,reboot) 查看网卡的命令: ifconfig 开启网卡的命令: ifup eth0 修改ip ...
- (转)Java DecimalFormat 用法(数字格式化)
我们经常要将数字进行格式化,比如取2位小数,这是最常见的.Java 提供 DecimalFormat 类,帮你用最快的速度将数字格式化为你需要的样子.下面是常用的例子: import java.tex ...
- PHP 错误日志
display_errors 错误回显,一般常用语开发模式,但是很多应用在正式环境中也忘记了关闭此选项.错误回显可以暴露出非常多的敏感信息,为攻击者下一步攻击提供便利.推荐关闭此选项. display ...
- LINux网络的NAPI机制详解一
在查看NAPI机制的时候发现一篇介绍NAPI引入初衷的文章写的很好,通俗易懂,就想要分享下,重要的是博主还做了可以在他基础上任意修改,而并不用注明出处的声明,着实令我敬佩,不过还是附上原文链接! ht ...