1、mybatis 通过 代码生成:
工具下载地址:
https://code.google.com/p/mybatis/
解压工具包 找到lib目录 添加 配置文件,根据文档说明执行代码生成:
2、mybatis 增改查:
项目结构:
config.properties:
db.driver=com.mysql.jdbc.Driverdb.url=jdbc:mysql://localhost:3306/mybatistest?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNulldb.user=rootdb.pass=wangkun
SqlMapConfig.xml
MyUserMapper.xml:
ID, UserName, CreateTime delete from myuser where ID = #{id,jdbcType=TINYINT} insert into myuser (ID, UserName, CreateTime ) values (#{id,jdbcType=TINYINT}, #{username,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP} ) insert into myuser ID, UserName, CreateTime, #{id,jdbcType=TINYINT}, #{username,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, update myuser where ID = #{id,jdbcType=TINYINT} UserName = #{username,jdbcType=VARCHAR}, CreateTime = #{createtime,jdbcType=TIMESTAMP}, update myuser set UserName = #{username,jdbcType=VARCHAR}, CreateTime = #{createtime,jdbcType=TIMESTAMP} where ID = #{id,jdbcType=TINYINT}
测试代码:
private static SqlSessionFactory sqlSessionFactory = null; static{ try { InputStream is= org.apache.ibatis.io.Resources.getResourceAsStream("SqlMapConfig.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(is); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /** * 添加数据 */ public static void testInsert() { SqlSession session=sqlSessionFactory.openSession(); MyUser user=new MyUser(); user.setCreatetime(new Date()); user.setUsername("RHYTHMK"); session.insert("insert",user); session.commit(); } /** * 查询数据 */ public static void testSelectOne() { SqlSession session=sqlSessionFactory.openSession(); try { MyUser user=session.selectOne("selectByPrimaryKey",1); System.out.printf(user.getUsername()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ session.close(); } } /** * 修改数据 */ public static void testUpdate() { SqlSession session=sqlSessionFactory.openSession(); MyUser user=new MyUser(); user.setCreatetime(new Date()); user.setUsername("RHYTHMK_update"); user.setId(Byte.parseByte("1")); session.insert("updateByPrimaryKeySelective",user); session.commit(); } public static void testSelectByMap() { Mapmap=new HashMap (); map.put("id", "2"); map.put("UserName", "wangk2"); SqlSession session=sqlSessionFactory.openSession(); MyUser user=(MyUser)session.selectOne("selectUser", map) ; System.out.println("testSelect:"+user.getId().toString()); }
相关代码:
http://pan.baidu.com/s/1raUGs