您的位置:首页 > 数据库

MyBatis操作数据库——单表映射操作

2016-10-09 11:03 190 查看
建立一张表subjects,包含基本信息 subjects.sql

SET FOREIGN_KEY_CHECKS=0;

# ------------- subjects table --------------------
DROP TABLE IF EXISTS subjects;
CREATE TABLE subjects
(
id         int          NOT NULL ,
name       varchar(20)  NOT NULL ,
sex        char(2)      NULL ,
birthday   char(50)     NULL ,
age        int          NULL ,
id_card    char(18)     NULL ,
tel        char(20)     NULL ,
date       char(50)     NULL ,
height     int          NULL ,
weight     int          NULL ,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into subjects values(0,'被试0','女','19951003',20,'12345678901','18399992222','20161008',162,50);
insert into subjects values(1,'被试1','女','19951003',20,'12345678901','18399992222','20161008',162,50);


新建 Java project,导入jar(myBatis\log4j\JUnit)包。



配置文件(log4j.properties\jdbc.properties)

注意:日志配置文件放在src根目录下,否则找不到;jdbc数据库连接配置信息中key-value中的value不要加“ ”; url后面要跟编码参数,否则中文编码会出错。

log4j.properies

# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
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


jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf8
jdbc.username =root
jdbc.password =


编写mysql_config.xml 主配置文件,config约束,jdbc连接。

<?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>
<!-- 加载属性文件 -->
<properties resource="config/jdbc.properties"></properties>

<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务控制由mybatis -->
<transactionManager type="JDBC" />

<!-- 数据库连接池,由mybatis管理 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>

<!-- 加载映射文件 -->
<mappers>
<mapper resource="dao/subjectMapper.xml"></mapper>
</mappers>

</configuration>


创建subjectMapper.xml文件,mapper约束,在Mapper根标签中创建select标签 sql查询。(id,parameterType,resultType)

<?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="subject">

<select id="findById" parameterType="java.lang.Integer" resultType="model.Subject">
select * from subjects where id = #{id}
</select>

<select id="findByName" parameterType="java.lang.String" resultType="model.Subject">
<!-- select * from subjects where name like CONCAT('%',#{name},'%')-->
select * from subjects where name like "%被试%"
</select>

</mapper>


因为select返回类型为对象,创建model.subject类。

package model;

public class Subject {

private int id;
private String name;      //����
private String sex;
private String birthday;
private int age;
private String id_card;  //���֤��
private String tel;
private String date;     //�������
private int height;
private int weight;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//省略setter,getter
}


编写Test类,通过JUnit注解@Test进行测试。

public class subjectMapperTest {

// 根据id查询被试,得到一条结果
@Test
public void findsubjectById() throws IOException{
//创建会话工厂
String resource = "config/mysqlMapper_config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();

Subject sub = sqlSession.selectOne("subject.findById",1);
System.out.println(sub);
sqlSession.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: