MyBatis的使用
1.导入jar包
包括(1)mybatis框架包:mybatismybatis-3.0.5.jar
(2)数据库驱动:mysql-connector-java-5.1.7-bin.jar(以mysql为例)
2.建立conf包,在其下建立配置文件:mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
4 <configuration>
5 <properties>
6 <property name="username" value="root"/>
7 <property name="password" value="root"/>
8 <property name="url" value="jdbc:mysql://localhost:3306/classification?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=round"/>
9 <property name="driver" value="com.mysql.jdbc.Driver"/>
10 </properties>
11 <environments default="development">
12
13 <environment id="development">
14 <transactionManager type="JDBC"/>
15 <dataSource type="POOLED">
16 <property name="driver" value="${driver}"/>
17 <property name="url" value="${url}"/>
18 <property name="username" value="${username}"/>
19 <property name="password" value="${password}"/>
20 <property name="poolMaximumActiveConnections" value="10"/>
21 <property name="poolMaximumIdleConnections" value="3"/>
22 </dataSource>
23 </environment>
24 </environments>
25 <mappers>
26 <mapper resource="classification/conf/textclassification.xml"/>
27 </mappers>
28 </configuration>
3.建立mapper(或者dao)包编写映射文件:mapper.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
4 <mapper namespace="textclassification">
5 <!-- textclassification start -->
6
7 <insert id="save_article_data" parameterType="classification.bean.Article">
8 insert into
9 tb_article(title,type)
10 values(#{title},#{type})
11 </insert>
12
13 <insert id="save_content_data" parameterType="classification.bean.Content">
14 insert into
15 tb_content(word,frequency,belong)
16 values(#{word},#{frequency},#{belong})
17 </insert>
18
19 <select id="get_allwords_data" resultType="String">
20 select distinct word from tb_content
21 </select>
22
23 <select id="get_singlewords_data" parameterType="String"
24 resultType="classification.bean.Content" useCache="true">
25 select word,frequency from tb_content where belong=#{belong}
26 </select>
27
28 </mapper>
4.在数据库中建表(以上为例,需要建立tb_article和tb_content两个表)
5.在函数中使用mybatis:
1 //配置
2 String resource = "classification/conf/mybatis.xml";
3 try {
4 reader = Resources.getResourceAsReader(resource);
5 } catch (IOException e) {
6 e.printStackTrace();
7 }
8 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
9 .build(reader);
10
11 SqlSession session = sessionFactory.openSession();
12
13
14
15 //调用
16 try
17 {
18 try {
19 session.insert("save_article_data", article);
20 } catch (Exception e) {
21 e.printStackTrace();
22 }
23 } catch (Exception e) {
24 // TODO: handle exception
25 e.printStackTrace();
26 } finally {
27 session.close();
28 }