| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1860 人关注过本帖
标题:mybatis编程
只看楼主 加入收藏
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
结帖率:40%
收藏
 问题点数:0 回复次数:8 
mybatis编程
Drop TABLE IF EXISTS `article`;
Create TABLE `article` (
  `id` int(11) NOT NULL auto_increment,
  `userid` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


Insert INTO `article` VALUES ('1', '1', 'test_title', 'test_content');
Insert INTO `article` VALUES ('2', '1', 'test_title_2', 'test_content_2');
Insert INTO `article` VALUES ('3', '1', 'test_title_3', 'test_content_3');
Insert INTO `article` VALUES ('4', '1', 'test_title_4', 'test_content_4');


Create TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


Insert INTO `user` VALUES ('1', 'summer', '100', 'shanghai,pudong');
搜索更多相关主题的帖子: article content Create title 
2013-11-08 14:03
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration PUBLIC "-// Config 3.0//EN"
 "http://
 <configuration>
     <typeAliases>
         <typeAlias alias="User" type="com.pojo.User"/>
         <typeAlias alias="Article" type="com.pojo.Article"/>  
     </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://127.0.0.1:3309/mybatis" />
                 <property name="username" value="root"/>
                 <property name="password" value="123"/>
             </dataSource>
         </environment>
     </environments>
     
     <mappers>
         <mapper resource="com/pojo/map.xml"/>
         <mapper class="com.IUserOperation"/>
     </mappers>
 </configuration>
2013-11-08 14:04
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 

  "http://
 
      
         
           
      
     
 
   
         
            
            
                 
                 
    <?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN"
 "http://






<mapper namespace="com.UserMapper">
    <!-- 为了返回list 类型而定义的returnMap -->
    <resultMap type="User" id="resultListUser">
        <id column="id" property="id" />
        <result column="userName" property="userName" />
        <result column="userAge" property="userAge" />
        <result column="userAddress" property="userAddress" />
    </resultMap>

    <!-- 返回list 的select 语句,用map传递多个参数自定义键名字 -->
    <parameterMap type="map" id="parammap">
        <parameter property="start" javaType="int" jdbcType="NUMERIC" />
        <parameter property="length" javaType="int" jdbcType="NUMERIC" />
    </parameterMap>

    <!-- 返回User 的select 语句,直接传递一个参数 -->
    <select id="selectUserByID" parameterType="int" resultType="User">
        select * from `user` where id = #{id}
    </select>

    <!-- 返回list 的select 语句,直接传递一个参数,注意 resultMap 的值是指向前面定义好的 -->
    <select id="selectUsers" parameterType="string" resultMap="resultListUser">
        select * from user where userName like #{userName}
    </select>

    <!-- 返回list 的select 语句,用map传递多个参数默认键名字 -->
    <select id="selectUserpage" parameterType="hashmap" resultMap="resultListUser">
        select * from user limit #{start},#{length}
    </select>

    <!-- 返回list 的select 语句,用map传递多个参数指定键名字 -->
    <select id="selectUserpage1" parameterMap="parammap" resultMap="resultListUser">
        select * from user limit #{start},#{length}
    </select>

    <!-- 返回list 的select 语句,用list传递多个参数 -->
    <select id="selectUserpage2" resultMap="resultListUser">
        Select * from user where id in
        <foreach item="item" index="index" collection="list" open="("
            separator="," close=")"> #{item}
        </foreach>
    </select>

    <!-- 使用实体类User传递多个参数 -->
    <insert id="addUser" parameterType="User" useGeneratedKeys="true"
        keyProperty="id">
        insert into user(userName,userAge,userAddress)
        values(#{userName},#{userAge},#{userAddress})
    </insert>
   
    <!-- 使用实体类User传递多个参数 -->
    <update id="updateUser" parameterType="User">
        update user set
        userName=#{userName},userAge=#{userAge},userAddress=#{userAddress}
        where id=#{id}
    </update>
   
    <!-- 直接传递参数 -->
    <delete id="deleteUser" parameterType="int">
        delete from user where
        id=#{id}
    </delete>





    <!-- User 联合文章进行查询 方法之一的配置 (多对一的方式) -->
    <resultMap id="resultUserArticleList" type="Article">
        <id property="id" column="aid" />
        <result property="title" column="title" />
        <result property="content" column="content" />

        <association property="user" javaType="User">
            <id property="id" column="id" />
            <result property="userName" column="userName" />
            <result property="userAddress" column="userAddress" />
        </association>
    </resultMap>

    <!-- User 联合文章进行查询 方法之二的配置 (多对一的方式) -->
    <resultMap id="resultUserArticleList-2" type="Article">
        <id property="id" column="aid" />
        <result property="title" column="title" />
        <result property="content" column="content" />
        <association property="user" javaType="User" resultMap="resultListUser" />
    </resultMap>

    <select id="getUserArticles" parameterType="int"
        resultMap="resultUserArticleList-2">
        select user.id,user.userName,user.userAddress,article.id
        aid,article.title,article.content from user,article
        where
        user.id=article.userid and user.id=#{id}
    </select>



</mapper>
 
 

            
                 
            
         
     
     
     
         
         
     
 
2013-11-08 14:04
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com.pojo;

public class User {
     
     private int id;
     private String userName;
     private String userAge;
     private String userAddress;
     
     public int getId() {
         return id;
     }
     public void setId(int id) {
         this.id = id;
     }
     public String getUserName() {
         return userName;
     }
     public void setUserName(String userName) {
         this.userName = userName;
     }
     public String getUserAge() {
         return userAge;
     }
     public void setUserAge(String userAge) {
         this.userAge = userAge;
     }
     public String getUserAddress() {
         return userAddress;
     }
     public void setUserAddress(String userAddress) {
         this.userAddress = userAddress;
     }
 
}
 
2013-11-08 14:05
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com.pojo;

//多对一个user
public class Article {
    private int id;
    private User user;
    private String title;
    private String content;
   
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
   
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

}

2013-11-08 14:05
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com;

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


import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.pojo.Article;
import com.pojo.User;

public interface IUserOperation {
    //直接传递参数
    @Select("SELECT * FROM user WHERE id = #{id}")
    public User selectUserByID(int id);
    @Select("select * from user where userName like #{userName}")
    public List<User> selectUsers(String userName);
    //map传递多个参数(可以自定义键名)
    @Select("select * from user limit #{start},#{length}")
    public List<User> getUsersPage(HashMap<String, Integer> map);
    //注解直接传递多个参数
    @Select("select * from user order by \'${id}\' \'${dir}\' limit #{start},#{length}")
    public List<User> getUsersPage1(@Param("id") String id,//排序字段
            @Param("dir") String dir,
            @Param("start") int start,
            @Param("length") int length);
    //list传递多个参数
    @Select("Select * from user limit #{list[0]},#{list[1]}")
    public List<User> getUserPageList(List<Integer> list);
    //传递实体对象类传递参数
    @Insert("insert into user(userName,userAge,userAddress) values (#{userName},#{userAge},#{userAddress})")
    public void addUser(User user);
    @Update("update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}")
    public void updateUser(User user);
    //直接传递参数
    @Delete("delete from user where id=#{id}")
    public void deleteUser(int id);
   
   
   
    //关联查询
    @Select("select article.id,user.id,user.userName,user.userAddress,article.title,article.content from user,article where user.id=article.userid and user.id=#{id}")
    public List<Article> getUserArticles(int id);
   
}
2013-11-08 14:05
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com;

import

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


public class SessionFactory {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }
}
2013-11-08 14:05
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.pojo.Article;
import com.pojo.User;

public class test {
    SqlSessionFactory sesionfactory=SessionFactory.getSession();
    public void getUser(int id) {
        SqlSession session = sesionfactory.openSession();
        try {

            User user = (User) session.selectOne(
                    "com.UserMapper.selectUserByID", "1");
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }
   
    public void getUserpage(int start,int len) {
        SqlSession session = sesionfactory.openSession();
        try {
             HashMap<String, Integer> map=new HashMap<String, Integer>();
                map.put("start", start);
                map.put("length", len);
             List<User> users = session.selectList(
                    "com.UserMapper.selectUserpage1", map);
             for (User user : users) {
                    System.out.println(user.getId() + ":" + user.getUserName()
                            + ":" + user.getUserAddress());
                }
        } finally {
            session.close();
        }
    }
   
    public void getUserpage1(int start,int len) {
        SqlSession session = sesionfactory.openSession();
        try {
             HashMap<String, Integer> map=new HashMap<String, Integer>();
                map.put("start", start);
                map.put("length", len);
             List<User> users = session.selectList(
                    "com.UserMapper.selectUserpage", map);
             for (User user : users) {
                    System.out.println(user.getId() + ":" + user.getUserName()
                            + ":" + user.getUserAddress());
                }
        } finally {
            session.close();
        }
    }
   
     public void getUsersPage2(int start,int len){
            SqlSession session = sesionfactory.openSession();
            try {
                List<Integer> list=new ArrayList<Integer>();
                list.add(start);
                list.add(len);
                List<User> users = session.selectList(
                        "com.UserMapper.selectUserpage2", list);
                for(User user:users){
                    System.out.println(user.getId()+":"+user.getUserName()
                            );
                }
            } finally {
                session.close();
            }
        }
   
    public void getUserList(String userName) {
        SqlSession session = sesionfactory.openSession();
        try {

            List<User> users = session.selectList(
                    "com.UserMapper.selectUsers", "summer");
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }
   
     public void addUser(){
            User user=new User();
            user.setUserAddress("人民广场");
            user.setUserName("飞鸟");
            user.setUserAge("80");
            SqlSession session = sesionfactory.openSession();
            try {
                session.insert("com.UserMapper.addUser", user);
                ();
                System.out.println("当前增加的用户 id为:"+user.getId());
            } finally {
                session.close();
            }
        }
     
     public void updateUser(){
            //先得到用户,然后修改,提交。
            SqlSession session =sesionfactory.openSession();
            try {
                User user = (User) session.selectOne(
                        "com.UserMapper.selectUserByID", "2");   
                user.setUserAddress("原来是魔都的浦东创新园区");
                session.update("com.UserMapper.updateUser", user);
                ();
               
            } finally {
                session.close();
            }
        }

     /**
         * 删除数据,删除一定要 commit.
         * @param id
         */
        public void deleteUser(int id){
            SqlSession session = sesionfactory.openSession();
            try {
                session.delete("com.UserMapper.deleteUser", id);         
                ();            
            } finally {
                session.close();
            }
        }

        public void getUserArticles(int userid){
            SqlSession session = sesionfactory.openSession();
            try {
                List<Article> articles = session.selectList("com.UserMapper.getUserArticles", userid);
                for(Article article:articles){
                    System.out.println(article.getTitle()+":"+article.getContent()+
                            ":作者是:"+article.getUser().getUserName()
                            );
                }
            } finally {
                session.close();
            }
        }
    public static void main(String[] args) {
        test testUser=new test();
        testUser.getUser(1);
        testUser.getUserList("%");
        //testUser.addUser();
        //testUser.updateUser();
        //testUser.deleteUser(4);
        //testUser.getUserArticles(1);
        //testUser.getUserpage(1,1);
        //testUser.getUserpage1(1,1);
        testUser.getUsersPage2(1, 2);

    }
}
2013-11-08 14:06
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
package com;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.pojo.Article;
import com.pojo.User;

public class test1 {
    SqlSessionFactory sesionfactory = SessionFactory.getSession();

    public void getUserList(String userName) {
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<User> users = userOperation.selectUsers("summer");
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName()
                        + ":" + user.getUserAddress());
            }

        } finally {
            session.close();
        }
    }

    public void getUser(int id) {
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = (IUserOperation) session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }

    public void getUsersPage(int start, int len) {
        SqlSession session = sesionfactory.openSession();
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("start", start);
        map.put("length", len);
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<User> users = userOperation.getUsersPage(map);
            for (User user : users) {
                System.out.println(user.getId() + ":" + user.getUserName());
            }
        } finally {
            session.close();
        }
    }
   
    public void getUsersPage1(int start,int len){
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation=session.getMapper(IUserOperation.class);           
            List<User> users = userOperation.getUsersPage1("id","userName",start,len);
            for(User user:users){
                System.out.println(user.getId()+":"+user.getUserName()
                        );
            }
        } finally {
            session.close();
        }
    }
   
    public void getUserPage2(int start,int len){
        SqlSession session = sesionfactory.openSession();
        try {
            List<Integer> list=new ArrayList<Integer>();
            list.add(start);
            list.add(len);
            IUserOperation userOperation=session.getMapper(IUserOperation.class);           
            List<User> users = userOperation.getUserPageList(list);
            for(User user:users){
                System.out.println(user.getId()+":"+user.getUserName()
                        );
            }
        } finally {
            session.close();
        }
    }
   


    public void addUser() {
        User user = new User();
        user.setUserAddress("人民广场");
        user.setUserName("飞鸟");
        user.setUserAge("80");
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.addUser(user);
            ();
            System.out.println("当前增加的用户 id为:" + user.getId());
        } finally {
            session.close();
        }
    }

    public void updateUser() {
        // 先得到用户,然后修改,提交。
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(3);
            user.setUserAddress("原来是魔都的浦东创新园区");
            userOperation.updateUser(user);
            ();

        } finally {
            session.close();
        }
    }

    /**
     * 删除数据,删除一定要 commit.
     *
     * @param id
     */
    public void deleteUser(int id) {
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            userOperation.deleteUser(id);
            ();
        } finally {
            session.close();
        }
    }

    public void getUserArticles(int userid) {
        SqlSession session = sesionfactory.openSession();
        try {
            IUserOperation userOperation = session
                    .getMapper(IUserOperation.class);
            List<Article> articles = userOperation.getUserArticles(userid);
            for (Article article : articles) {
                System.out.println(article.getTitle() + ":"
                        + article.getContent() + ":作者是:" + article.getUser());
            }
        } finally {
            session.close();
        }
    }

    public static void main(String[] args) {

        test1 testUser = new test1();
        testUser.getUser(1);
        testUser.getUserList("%");
        // testUser.getUserArticles(1);
        //testUser.getUsersPage(1, 1);
        //testUser.getUsersPage1(1,1);
        testUser.getUserPage2(1,2);
        // testUser.addUser();
        // testUser.updateUser();
        // testUser.deleteUser(5);

    }

}
2013-11-08 14:06
快速回复:mybatis编程
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.042583 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved