Ibatis基础学习案例

来源:互联网 发布:阿里巴巴数据库多大 编辑:程序博客网 时间:2024/06/07 07:15

这是一个完整的案例,可以运行。

Ibtis的核心包Sqlconfig.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="Author" type="org.mybatis.model.Author"/>
    <typeAlias alias="Blog" type="org.mybatis.model.Blog"/>
    <typeAlias alias="Comment" type="org.mybatis.model.Comment"/>
    <typeAlias alias="Post" type="org.mybatis.model.Post"/>
    <typeAlias alias="Tag" type="org.mybatis.model.Tag"/>
  </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/blogdb?useUnicode=true&amp;characterEncoding=UTF-8" />
    <property name="username" value="root" />
    <property name="password" value="Sun_1024" />
   </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/model/BlogMapper.xml"/>
<!--    <mapper resource="org/mybatis/model/AuthorMapper.xml"/> -->
<!--    <mapper resource="org/mybatis/model/PostMapper.xml"/> -->
  </mappers>
  </configuration>

 

实体类映射BlogMapper.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="org.mybatis.model.BlogMapper">

 <!--简单的几种查询-->
 <select id="selectBlog_by_id" parameterType="int" resultType="Blog">
  select * from Blog where id = #{id}
    </select>
 <select id="selectBlog_by_id_Map" parameterType="HashMap"
  resultType="Blog">
  select * from Blog where id = #{id}
    </select>

 <select id="selectBlog_by_bean" parameterType="Blog" resultType="Blog">

  select * from Blog where id = #{id}
   </select>

 <!--联合查询-->
 <!-- <resultMap id="blogResultMap" type="Blog">-->
 <!--  <id property="id" column="id" />-->
 <!--  <result property="title" column="title" />-->
 <!--  <result property="authorId" column="author_id" />-->
 <!-- </resultMap>-->
<!---->
 <!-- <select id="selectBlog_use_as" parameterType="HashMap"-->
 <!--  resultType="Blog">-->
 <!--  select id , title, author_id as authorid from Blog where id-->
 <!--  = #{id}-->
 <!--  </select>-->
<!---->
 <!-- <select id="selectBlog_use_resultMap" parameterType="HashMap"-->
 <!--  resultMap="blogResultMap">-->
 <!--  select id , title, author_id from Blog where id = #{id}-->
 <!-- </select>-->


 <!-- update,delete,insert操作 -->
 <update id="updateBlog_use_bean" statementType="PREPARED"
  parameterType="Blog">
  update blog set title= #{title}, author_id=#{authorId}
  where id =
  #{id} 
     </update>
 <delete id="deleteBlog_use_bean" statementType="PREPARED"
  parameterType="Blog">
  delete from blog where id = #{id}
     </delete>
 <insert id="insertBlog_user_bean" statementType="PREPARED"
  parameterType="Blog">

  insert into blog(id, title, author_id) values(#{id},
  #{title},
  #{authorId}) 
     </insert>

 

 <!--自动生成主键      下面是自动生成blog的id的值,生成规则是:当前表中最大的id值加1。 -->
 <!-- <insert id="insertBlog_user_autokey" statementType="PREPARED"-->
 <!--  parameterType="Blog">-->
 <!--  <selectKey keyProperty="id" resultType="int" order="BEFORE">-->
 <!--   select-->
 <!--   max(id)+1 from blog -->
 <!--        </selectKey>-->
 <!--  insert into blog(title, author_id) values(#{id}, #{title},-->
 <!--  #{authorId})-->
 <!-- </insert>-->


 <!-- 处理NULL值    像上面的例子,如果myBlog.setTitle(null)情况会怎样呢?那么程序会报错:-->
 <insert id="insertBlog_user_autokey" statementType="PREPARED"
  parameterType="Blog" flushCache="true">
  <selectKey keyProperty="id" resultType="int" order="BEFORE">
   select
   max(id)+1 from blog
      </selectKey>
  insert into blog(id, title, author_id) values(#{id},
  #{title,jdbcType=VARCHAR},
  #{authorId})
 </insert>


 <!--
  使用Constructor元素是将数据库查询的结果通过构造器注入到结果映射类(JavaBean) 中,可以理解为spring中的构造器注入
 -->
 <resultMap id="blogResultMap" type="Blog">
  <constructor>
   <idArg column="id" javaType="int" />
   <arg column="title" javaType="String" />
   <arg column="author_id" javaType="int" />
  </constructor>

 </resultMap>

 <select id="selectBlog_use_constructor" resultMap="blogResultMap">
  select id ,
  title, author_id from Blog where id = #{id}
    </select>


 <!--
  � 使用Association元素 一个作者有一个博客,这是种“has-a”的一对一关系,现在我们使用Association元素把博
  客及作者的信息查询出来-
 -->

 <!-- 方案一 -->
 <!-- <resultMap id="blogResult" type="Blog">-->
 <!--  <id property="id" column="blog_id" />-->
 <!--  <result property="title" column="blog_title" />-->
<!---->
 <!--  <association property="author" javaType="Author">-->
 <!--   <id property="id" column="author_id" />-->
 <!--   <result property="username" column="author_username" />-->
 <!--   <result property="password" column="author_password" />-->
 <!--   <result property="email" column="author_email" />-->
 <!--   <result property="bio" column="author_bio" />-->
 <!--  </association>-->
 <!-- </resultMap>-->
<!---->
 <!-- <select id="selectBlog_use_association" parameterType="int"-->
 <!--  resultMap="blogResult">-->
 <!--  select-->
 <!--  B.id as blog_id,-->
 <!--  B.title as blog_title,-->
<!---->
 <!--  A.id as-->
 <!--  author_id,-->
 <!--  A.username as author_username,-->
 <!--  A.password as author_password,-->
 <!--  A.email as author_email,-->
 <!--  A.bio as author_bio-->
 <!--  from Blog B left outer join-->
 <!--  Author A on B.author_id = A.id-->
 <!--  where B.id = #{id} -->
 <!--  </select>-->


 <!-- 方案二 -->
 <!-- <resultMap id="blogResult" type="Blog">-->
 <!--  <id property="id" column="blog_id" />-->
 <!--  <result property="title" column="blog_title" />-->
 <!--  <association property="author" column="blog_author_id"-->
 <!--   javaType="Author" resultMap="authorResult" />-->
 <!-- </resultMap>-->
<!---->
 <!-- <resultMap id="authorResult" type="Author">-->
 <!--  <id property="id" column="author_id" />-->
 <!--  <result property="username" column="author_username" />-->
 <!--  <result property="password" column="author_password" />-->
 <!--  <result property="email" column="author_email" />-->
 <!--  <result property="bio" column="author_bio" />-->
 <!-- </resultMap>-->
<!---->
 <!-- <select id="selectBlog_use_association" parameterType="int"-->
 <!--  resultMap="blogResult">-->
 <!--  select-->
 <!--  B.id as blog_id,-->
 <!--  B.title as blog_title,-->
 <!--  A.id as-->
 <!--  author_id,-->
 <!--  A.username as author_username,-->
 <!--  A.password as author_password,-->
 <!--  A.email as author_email,-->
 <!--  A.bio as author_bio-->
 <!--  from Blog B left outer join-->
 <!--  Author A on B.author_id = A.id-->
 <!--  where B.id = #{id} -->
 <!--  </select>-->


 <!-- 方案三 -->
 <!-- <resultMap id="blogResult" type="Blog">-->
 <!--  <association property="author" column="author_id"-->
 <!--   javaType="Author" select="selectAuthor" />-->
 <!-- </resultMap>-->
 <!--
  <select id="selectAuthor" parameterType="int" resultType="Author">
 -->
 <!--  SELECT-->
 <!--  * FROM AUTHOR WHERE ID = #{id} -->
 <!--       </select>-->
 <!-- <select id="selectBlog_use_association" parameterType="int"-->
 <!--  resultMap="blogResult">-->
 <!--  SELECT * FROM BLOG WHERE ID = #{id} -->
 <!--    </select>-->

 <!--
  方案三中如果"selectBlog_use_association"查询返回N条博客记录,修改一下。
  注:如果SQL语句有特殊符号,需要用<![CDATA[]]>括起来。这里的小于号<被认为
  是特殊符号,如果不用<![CDATA[]]>括起来是执行不了的 ,调用代码也相应的改变
 -->
 <!-- <resultMap id="blogResult" type="Blog">-->
 <!--  <association property="author" column="author_id"-->
 <!--   javaType="Author" select="selectAuthor" />-->
 <!-- </resultMap>-->
 <!--
  <select id="selectAuthor" parameterType="int" resultType="Author">
 -->
 <!--  SELECT-->
 <!--  * FROM AUTHOR WHERE ID = #{id} -->
 <!--       </select>-->
 <!-- <select id="selectBlog_use_association" resultMap="blogResult"> -->
 <!--
  <![CDATA[SELECT * FROM BLOG WHERE ID > 0 and ID < 7]]>
 -->
 <!-- </select>-->

 <!--
  使用Collection元素 Collection元素用来处理“一对多”的数据模型,例如,一个博客有许多文章(Posts)。
  在博客类里,应该有一个文章的列表
 -->

 <!--方案一-->
 <!-- <resultMap id="blogResult" type="Blog">-->
 <!--  <id property="id" column="id" />-->
 <!--  <result property="title" column="title" />-->
 <!--  <result property="authorId" column="authorid" />-->
 <!--  <collection property="posts" javaType="ArrayList" column="id"-->
 <!--   ofType="Post" select="selectPostsForBlog" />-->
 <!-- </resultMap>-->
<!---->
 <!--
  <select id="selectPostsForBlog" parameterType="int" resultType="Post">
 -->
 <!--  SELECT * FROM POST WHERE BLOG_ID = #{id} -->
 <!--       </select>-->
<!---->
 <!-- <select id="selectBlog_use_collection" resultMap="blogResult"> -->
 <!--
  <![CDATA[SELECT id , title, author_id as authorid FROM BLOG WHERE ID >
  0 and ID
 -->
 <!--< 4]]>-->
 <!-- </select>-->


 <!--方案二-->
  <resultMap id="blogResult" type="Blog">
   <id property="id" column="blog_id" />
   <result property="title" column="blog_title" />
   <result property="authorId" column="authorid" />
   <collection property="posts" ofType="Post">
    <id property="id" column="post_id" />
    <result property="subject" column="post_subject" />
    <result property="section" column="post_section" />
    <result property="body" column="post_body" />
   </collection>
  </resultMap>

  <select id="selectBlog_use_collection" resultMap="blogResult">
         <![CDATA[
               select
                   B.id as blog_id,
                  
                   B.title as blog_title,
                   B.author_id as authorid,
                   P.id as post_id,
                   P.subject as post_subject,
                   P.section as post_section,
                   P.body as post_body
            from Blog B
            left outer join Post P on B.id = P.blog_id
            where B.id > 0 and B.id < 4]]>
  </select>
</mapper>


 

Author类

package org.mybatis.model;

public class Author {
 private Integer id;

 private String username;

 private String password;

 private String email;

 private String bio;

 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 getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getBio() {
  return bio;
 }

 public void setBio(String bio) {
  this.bio = bio;
 }
}

 

Blog类

package org.mybatis.model;

import java.util.List;

public class Blog {
 private Integer id;

    private String title;

    private Integer authorId;

    private Author author;
   
    private List<Post> posts ;
   
 public Blog() {
  super();
 }

 public Blog(Integer id, String title, Integer authorId) {
  super();
  this.id = id;
  this.title = title;
  this.authorId = authorId;
 }

 public Author getAuthor() {
  return author;
 }

 public Integer getAuthorId() {
  return authorId;
 }

 public Integer getId() {
  return id;
 }

 public String getTitle() {
  return title;
 }

 public void setAuthor(Author author) {
  this.author = author;
 }

 public void setAuthorId(Integer authorId) {
  this.authorId = authorId;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public void setPosts(List<Post> posts) {
  this.posts = posts;
 }

 public List<Post> getPosts() {
  return posts;
 }
}

 

Post类

package org.mybatis.model;

public class Post {
  private Integer id;

     private Integer blogId;

     private Integer authorId;

     private String createdOn;

     private String section;

     private String subject;

     private String body;

 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public Integer getBlogId() {
  return blogId;
 }

 public void setBlogId(Integer blogId) {
  this.blogId = blogId;
 }

 public Integer getAuthorId() {
  return authorId;
 }

 public void setAuthorId(Integer authorId) {
  this.authorId = authorId;
 }

 public String getCreatedOn() {
  return createdOn;
 }

 public void setCreatedOn(String createdOn) {
  this.createdOn = createdOn;
 }

 public String getSection() {
  return section;
 }

 public void setSection(String section) {
  this.section = section;
 }

 public String getSubject() {
  return subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 public String getBody() {
  return body;
 }

 public void setBody(String body) {
  this.body = body;
 }
}

 

SimpleMapper类

package org.mybatis.action;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.BasicConfigurator;
import org.mybatis.model.Blog;
import org.mybatis.model.BlogMapper;
import org.mybatis.model.Post;
import org.mybatis.service.SqlMapperManager;

public class SimpleMapper {
 /**
  * @param args
  */
 public static void main(String[] args) {
  BasicConfigurator.configure();
  SqlSession session = null;
  Blog blog = null;
  try {
   SqlSessionFactory factory = SqlMapperManager.getFactory();
   if (factory == null) {
    System.out.println("get SqlSessionFactory failed.");
    return;
   }
   session = factory.openSession();
   

下面的代码中有//注释掉的按功能去掉


   // HashMap<String, Integer> paramMap = new HashMap<String,
   // Integer>();
   // paramMap.put("id", 2);
   //
   // Blog myBlog = new Blog();
   // myBlog.setId(3);
   //
   // blog = (Blog) session.selectOne("selectBlog_by_id", 1);
   // pringBlog(blog);
   //
   // blog = (Blog) session.selectOne("selectBlog_by_id_Map",
   // paramMap);
   // pringBlog(blog);
   //
   // blog = (Blog) session.selectOne("selectBlog_by_bean", myBlog);
   // pringBlog(blog);

   // HashMap<String, Integer> paramMap = new HashMap<String,
   // Integer>();
   // paramMap.put("id", 2);
   //
   // Blog myBlog = new Blog();
   // myBlog.setId(3);
   //
   // blog = (Blog) session.selectOne("selectBlog_use_as", myBlog);
   // pringBlog(blog);
   //
   // blog = (Blog) session.selectOne("selectBlog_use_resultMap",
   // paramMap);
   // pringBlog(blog);
   
   
   
   
//   Blog myBlog = new Blog();
//   myBlog.setId(3);
//   myBlog.setTitle("I Love Photh");
//   myBlog.setAuthorId(3);
//
//   session.update("updateBlog_use_bean", myBlog); session.commit();
//   session.delete("deleteBlog_use_bean", myBlog); session.commit();
//   session.insert("insertBlog_user_bean", myBlog);  session.commit();  
  
//    Blog myBlog1 = new Blog();
//    myBlog1.setTitle("I Love Photh");
//    myBlog1.setAuthorId(3);
//    session.insert("insertBlog_user_autokey", myBlog1);
//    session.insert("insertBlog_user_autokey", myBlog1);
//    session.insert("insertBlog_user_autokey", myBlog1);
   
   
   
   //SimpleMapper.userMapper(session);
   
   
   //使用Constructor元素是将数据库查询的结果通过构造器注入到结果映射类(JavaBean) 中,的测试
//   blog = (Blog)session.selectOne("selectBlog_use_constructor", 3);
//   pringBlog(blog);

   //查询返回1条博客记录
//   blog = (Blog)session.selectOne("selectBlog_use_association", 3);
//    printBlogAuthor(blog);

   
    //查询返回N条博客记录
//    List<Blog> blogList = (List<Blog>)session.selectList("selectBlog_use_association");
//    printBlogAuthorList(blogList);
   
   
   //使用Collection元素 Collection元素用来处理“一对多”的数据模型
    List<Blog> blogList = (List<Blog>)session.selectList("selectBlog_use_collection");
    printBlogPosts(blogList);
   
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   session.close();
  }
 }

 public static void pringBlog(Blog blog) {
  if (blog != null) {
   System.out.println("ID:" + blog.getId());
   System.out.println("title:" + blog.getTitle());
   System.out.println("authorID:" + blog.getAuthorId());   
   
  } else {
   System.out.println("blog=null");
  }
 }
 
 /**
  * 使用接口映射类      对给定的映射语句,使用一个正确描述参数与返回值的接口(如BlogMapper.class)
  * @param session
  */
  public static void userMapper(SqlSession session)
     {
            Blog blog = new Blog();
            blog.setTitle("nothing title");
            blog.setId(1);
            blog.setAuthorId(1);

            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            Blog blog1 = blogMapper.selectBlog_by_id(1);
            pringBlog(blog1);

            blogMapper.updateBlog_use_bean(blog);

            blog1 = blogMapper.selectBlog_by_id(1);
            pringBlog(blog1);
     }

 
  /**
   * 查询返回1条博客记录
   * @param blog
   */
  public static void printBlogAuthor(Blog blog)
  {
         System.out.println("ID:" + blog.getId());
         System.out.println("title:" + blog.getTitle());
         System.out.println("authorID:" + blog.getAuthor().getId());
         System.out.println("authorName:" + blog.getAuthor().getUsername());
         System.out.println("authorPassword:" + blog.getAuthor().getPassword());
         System.out.println("authorEmail:" + blog.getAuthor().getEmail());
         System.out.println("authorBio:" + blog.getAuthor().getBio());
  }
 
 
  /**
   * 查询返回N条博客记录
   * @param blogList
   */

  public static void printBlogAuthorList(List<Blog> blogList)
  {
      for (Blog blog : blogList)
      {
         System.out.println("===========================");
         System.out.println("ID:" + blog.getId());
         System.out.println("title:" + blog.getTitle());
         System.out.println("authorID:" + blog.getAuthor().getId());
         System.out.println("authorName:" + blog.getAuthor().getUsername());
         System.out.println("authorPassword:" + blog.getAuthor().getPassword());
         System.out.println("authorEmail:" + blog.getAuthor().getEmail());
         System.out.println("authorBio:" + blog.getAuthor().getBio());
      }
  }
 
 
 
  /**
   * 使用Collection元素 Collection元素用来处理“一对多”的数据模型
   * @param blogList
   */
  public static void printBlogPosts(List<Blog> blogList)
  {
         for (Blog blog : blogList)
         {
                System.out.println("\n===========================");
                System.out.println("ID:" + blog.getId());
                System.out.println("blog_title:" + blog.getTitle());
                System.out.println("authorID:" + blog.getAuthorId());
                System.out.println("===========posts=============");

                for (Post post : blog.getPosts())
                {
                        System.out.println("subject:" + post.getSubject());
                        System.out.println("section:" + post.getSection());
                        System.out.println("body:" + post.getBody());
                }
         }
  }

}

 

 

SqlMapperManager类

package org.mybatis.service;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlMapperManager {
 private static SqlSessionFactory factory = null;
    private static String fileName = "Sqlconfig.xml";

    private SqlMapperManager()
    {

    }

    public static void initMapper(String sqlMapperFileName)
    {
           fileName = sqlMapperFileName;
    }

    public static SqlSessionFactory getFactory()
    {
           try
           {
                   if (factory == null)
                   {
                          Reader reader = Resources
                               .getResourceAsReader(fileName);
                          SqlSessionFactoryBuilder builder =
                                new SqlSessionFactoryBuilder();
                          factory = builder.build(reader);
                          builder = null;
                   }
           }
           catch (IOException e)
           {
                   e.printStackTrace();
                   return null;
           }
           return factory;
    }
}

原创粉丝点击