写在这个系列前面的话: 以前曾经用过ibatis,这是mybatis的前身,当时在做项目时,感觉很不错,比hibernate灵活。性能也比hibernate好。而且也比较轻量级,因为当时在项目中,没来的及做很很多笔记。后来项目结束了,我也没写总结文档。已经过去好久了。但最
写在这个系列前面的话:
以前曾经用过ibatis,这是mybatis的前身,当时在做项目时,感觉很不错,比hibernate灵活。性能也比hibernate好。而且也比较轻量级,因为当时在项目中,没来的及做很很多笔记。后来项目结束了,我也没写总结文档。已经过去好久了。但最近突然又对这个ORM 工具感兴趣。因为接下来自己的项目中很有可能采用这个ORM工具。所以在此重新温习了一下 mybatis, 因此就有了这个系列的 mybatis 教程.5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
package com.yihaomen.mybatis.model; 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; } }
package com.yihaomen.test; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.yihaomen.mybatis.model.User; public class Test { 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; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { User user = (User) session.selectOne("com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); } finally { session.close(); } } }
package com.yihaomen.mybatis.inter; import com.yihaomen.mybatis.model.User; public interface IUserOperation { public User selectUserByID(int id); }
public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); User user = userOperation.selectUserByID(1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); } finally { session.close(); } }
public void getUserList(String userName){ SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); Listusers = userOperation.selectUsers(userName); for(User user:users){ System.out.println(user.getId()+":"+user.getUserName()+":"+user.getUserAddress()); } } finally { session.close(); } }
public static void main(String[] args) { Test testUser=new Test(); testUser.getUserList("%"); }
insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress})
*/ public void addUser(){ User user=new User(); user.setUserAddress("人民广场"); user.setUserName("飞鸟"); user.setUserAge(80); SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); userOperation.addUser(user); session.commit(); System.out.println("当前增加的用户 id为:"+user.getId()); } finally { session.close(); } }
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
public void updateUser(){ //先得到用户,然后修改,提交。 SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); User user = userOperation.selectUserByID(4); user.setUserAddress("原来是魔都的浦东创新园区"); userOperation.updateUser(user); session.commit(); } finally { session.close(); } }
delete from user where id=#{id}
* @param id */ public void deleteUser(int id){ SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); userOperation.deleteUser(id); session.commit(); } finally { session.close(); } }
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');
package com.yihaomen.mybatis.model; 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; } }
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}
public void getUserArticles(int userid){ SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); Listarticles = userOperation.getUserArticles(userid); for(Article article:articles){ System.out.println(article.getTitle()+":"+article.getContent()+ ":作者是:"+article.getUser().getUserName()+":地址:"+ article.getUser().getUserAddress()); } } finally { session.close(); } }
package com.yihaomen.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yihaomen.mybatis.inter.IUserOperation; import com.yihaomen.mybatis.model.Article; import com.yihaomen.mybatis.model.User; public class MybatisSprintTest { private static ApplicationContext ctx; static { ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml"); } public static void main(String[] args) { IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper"); //测试id=1的用户查询,根据数据库中的情况,可以改成你自己的. System.out.println("得到用户id=1的用户信息"); User user = mapper.selectUserByID(1); System.out.println(user.getUserAddress()); //得到文章列表测试 System.out.println("得到用户id为1的所有文章列表"); Listarticles = mapper.getUserArticles(1); for(Article article:articles){ System.out.println(article.getContent()+"--"+article.getTitle()); } } }
contextConfigLocation classpath*:config/applicationContext.xml org.springframework.web.context.ContextLoaderListener org.springframework.web.context.ContextCleanupListener mvc-dispatcher org.springframework.web.servlet.DispatcherServlet 1 mvc-dispatcher /
/WEB-INF/pages/ .jsp
package com.yihaomen.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.yihaomen.inter.IUserOperation; import com.yihaomen.model.Article; @Controller @RequestMapping("/article") public class UserController { @Autowired IUserOperation userMapper; @RequestMapping("/list") public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){ Listarticles=userMapper.getUserArticles(1); ModelAndView mav=new ModelAndView("list"); mav.addObject("articles",articles); return mav; } }
[code] ${item.id }--${item.title }--${item.content }
package com.yihaomen.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.bind.PropertyException; import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.ExecutorException; import org.apache.ibatis.executor.statement.BaseStatementHandler; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ParameterMode; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.property.PropertyTokenizer; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) public class PagePlugin implements Interceptor { private static String dialect = ""; private static String pageSqlId = ""; @SuppressWarnings("unchecked") public Object intercept(Invocation ivk) throws Throwable { if (ivk.getTarget() instanceof RoutingStatementHandler) { RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk .getTarget(); BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper .getValueByFieldName(statementHandler, "delegate"); MappedStatement mappedStatement = (MappedStatement) ReflectHelper .getValueByFieldName(delegate, "mappedStatement"); if (mappedStatement.getId().matches(pageSqlId)) { BoundSql boundSql = delegate.getBoundSql(); Object parameterObject = boundSql.getParameterObject(); if (parameterObject == null) { throw new NullPointerException("parameterObject error"); } else { Connection connection = (Connection) ivk.getArgs()[0]; String sql = boundSql.getSql(); String countSql = "select count(0) from (" + sql + ") myCount"; System.out.println("总数sql 语句:"+countSql); PreparedStatement countStmt = connection .prepareStatement(countSql); BoundSql countBS = new BoundSql( mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject); setParameters(countStmt, mappedStatement, countBS, parameterObject); ResultSet rs = countStmt.executeQuery(); int count = 0; if (rs.next()) { count = rs.getInt(1); } rs.close(); countStmt.close(); PageInfo page = null; if (parameterObject instanceof PageInfo) { page = (PageInfo) parameterObject; page.setTotalResult(count); } else if(parameterObject instanceof Map){ Mapmap = (Map )parameterObject; page = (PageInfo)map.get("page"); if(page == null) page = new PageInfo(); page.setTotalResult(count); }else { Field pageField = ReflectHelper.getFieldByFieldName( parameterObject, "page"); if (pageField != null) { page = (PageInfo) ReflectHelper.getValueByFieldName( parameterObject, "page"); if (page == null) page = new PageInfo(); page.setTotalResult(count); ReflectHelper.setValueByFieldName(parameterObject, "page", page); } else { throw new NoSuchFieldException(parameterObject .getClass().getName()); } } String pageSql = generatePageSql(sql, page); System.out.println("page sql:"+pageSql); ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); } } } return ivk.proceed(); } private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException { ErrorContext.instance().activity("setting parameters") .object(mappedStatement.getParameterMap().getId()); List parameterMappings = boundSql .getParameterMappings(); if (parameterMappings != null) { Configuration configuration = mappedStatement.getConfiguration(); TypeHandlerRegistry typeHandlerRegistry = configuration .getTypeHandlerRegistry(); MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject); for (int i = 0; i "); pageSql.append(page.getCurrentResult()); } return pageSql.toString(); } else { return sql; } } public Object plugin(Object arg0) { // TODO Auto-generated method stub return Plugin.wrap(arg0, this); } public void setProperties(Properties p) { dialect = p.getProperty("dialect"); if (dialect ==null || dialect.equals("")) { try { throw new PropertyException("dialect property is not found!"); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } pageSqlId = p.getProperty("pageSqlId"); if (dialect ==null || dialect.equals("")) { try { throw new PropertyException("pageSqlId property is not found!"); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
@RequestMapping("/pagelist") public ModelAndView pageList(HttpServletRequest request,HttpServletResponse response){ int currentPage = request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page")); int pageSize = 3; if (currentPage articles=iUserOperation.selectArticleListPage(page,1); System.out.println(page); int totalCount = page.getTotalResult(); int lastPage=0; if (totalCount % pageSize==0){ lastPage = totalCount % pageSize; } else{ lastPage =1+ totalCount / pageSize; } if (currentPage>=lastPage){ currentPage =lastPage; } String pageStr = ""; pageStr=String.format("上一页 下一页", request.getRequestURI()+"?page="+(currentPage-1),request.getRequestURI()+"?page="+(currentPage+1) ); //制定视图,也就是list.jsp ModelAndView mav=new ModelAndView("list"); mav.addObject("articles",articles); mav.addObject("pageStr",pageStr); return mav; }
update t_blog where id = #{id} title = #{title}, content = #{content}, owner = #{owner}
@Test public void dynamicForeachTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Listids = new ArrayList (); ids.add(1); ids.add(3); ids.add(6); List blogs = blogMapper.dynamicForeachTest(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
Drop TABLE IF EXISTS `category`; Create TABLE `category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `catname` varchar(50) NOT NULL, `catdescription` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
已抢66326个
抢已抢36424个
抢已抢20230个
抢已抢2474个
抢已抢18893个
抢