예제 #1
0
 public SqlSession getSession() throws Exception {
   String resource = "myBatis-configuration.xml";
   Reader reader = Resources.getResourceAsReader(resource);
   SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
   SqlSessionFactory factory = builder.build(reader);
   return factory.openSession();
 }
예제 #2
0
  /** @param args */
  public static void main(String[] args) {

    InputStream inputStream = null;
    try {
      inputStream = Resources.getResourceAsStream("org/mybatis/example/config.properties");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Properties p = null;
    try {
      p = new Properties();
      // load file
      p.load(inputStream);
    } catch (Exception e) {
      e.printStackTrace();
    }

    String resource = "org/mybatis/example/mybatis-config.xml";

    try {
      inputStream = Resources.getResourceAsStream(resource);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, p);
    SqlSession session = sqlSessionFactory.openSession();
    try {
      Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    } finally {
      session.close();
    }
  }
예제 #3
0
 /**
  * 获取permission数据集合
  *
  * @author 尹逊志
  * @throws JsonProcessingException
  * @time 2015年4月13日下午10:29:36
  */
 @ResponseBody
 @RequestMapping(value = "/user/permissionList", method = RequestMethod.POST)
 public String getPermissonData(HttpServletRequest request, HttpServletResponse response)
     throws JsonProcessingException {
   String rows = request.getParameter("rows");
   String page = request.getParameter("page");
   if (rows == null) {
     rows = "20";
   }
   if (page == null) {
     page = "1";
   }
   String resource = "/mybatis-config-test.xml";
   InputStream is = UserController.class.getResourceAsStream(resource);
   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
   SqlSession session = factory.openSession();
   String statement = "com.myproject.mybatis.user.permissionMapper.getAll";
   Map<String, Integer> map = new HashMap<String, Integer>();
   map.put("pageNum", Integer.parseInt(page));
   map.put("pageSize", Integer.parseInt(rows));
   PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
   List<Permission> permissList = session.selectList(statement);
   PageInfo<Permission> pageInfo = new PageInfo<Permission>(permissList);
   session.commit();
   session.close();
   ResponseResult result = new ResponseResult();
   result.setTotal(pageInfo.getTotal());
   result.setRows(permissList);
   ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsString(result);
 }
예제 #4
0
  public static void main(String[] args) {
    Reader reader;
    try {
      reader = Resources.getResourceAsReader("mapper/Configuration.xml");
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
      DBSessionDao dbSessionDao = new DBSessionDao();
      System.out.println(" -------- " + dbSessionDao);

      SqlSession sqlSession = sqlSessionFactory.openSession(dbSessionDao.getConnection());
      // SqlSession sqlSession = sqlSessionFactory.openSession();
      System.out.println(sqlSession);

      OperatorMapper operatorMapper = sqlSession.getMapper(OperatorMapper.class);
      OperatorExample operatorExample = new OperatorExample();
      operatorExample.createCriteria().andOpernameEqualTo("tc");
      List<Operator> list = operatorMapper.selectByExample(operatorExample);
      for (Operator operator : list) {
        System.out.println("   2  " + operator);
      }

      sqlSession.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
예제 #5
0
파일: MyBatis.java 프로젝트: Godin/sonar
 /** @since 4.4 */
 public DbSession openSession(boolean batch) {
   if (batch) {
     SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);
     return new BatchSession(session);
   }
   SqlSession session = sessionFactory.openSession(ExecutorType.REUSE);
   return new DbSession(session);
 }
예제 #6
0
 @Test
 public void deleteUser() throws IOException {
   InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
   SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   SqlSession sqlSession = sessionFactory.openSession();
   sqlSession.delete("test.deleteUserById", 26);
   sqlSession.close();
 }
예제 #7
0
 @Test
 public void findUserById() throws IOException {
   InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
   SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   SqlSession sqlSession = sessionFactory.openSession();
   User user = sqlSession.selectOne("test.findUserId", 1);
   System.out.println(user);
   sqlSession.close();
 }
예제 #8
0
 @Test
 public void findUserByName() throws IOException {
   InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
   SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   SqlSession sqlSession = sessionFactory.openSession();
   List<User> list = sqlSession.selectList("test.findUserByName", "小");
   System.out.println(list);
   sqlSession.close();
 }
 public SqlSession getSession() {
   try {
     Reader reader = Resources.getResourceAsReader(resource);
     SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
     session = sqlMapper.openSession();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
   return session;
 }
예제 #10
0
파일: test.java 프로젝트: RAPIER512/Mybatis
  public static void main(String[] args) {

    String resource = "conf.xml";
    InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
    SqlSession session = factory.openSession();
    String statement = "com.mybatis.test1.userMapper.getUser";
    User user = session.selectOne(statement, 2);
    session.close();
    System.out.println(user);
  }
예제 #11
0
 public static SqlSession getSession() {
   String resource = "mybatisConfig.xml";
   InputStream is = null;
   try {
     is = Resources.getResourceAsStream(resource);
   } catch (IOException e) {
     e.printStackTrace();
   }
   SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
   return sessionFactory.openSession();
 }
예제 #12
0
 private SqlSession getBatchSqlSession(String componentName, String environment) {
   SqlSessionFactory sqlSessionFactory =
       this.getSqlSessionFactory(componentName, environment, false);
   long start = System.currentTimeMillis();
   SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
   long end = System.currentTimeMillis();
   if (end - start > 100) {
     LOG.warn("open sql session:" + environment + " " + (end - start) + " millionSeconds");
   }
   return session;
 }
예제 #13
0
 private SqlSession getSqlSession(String componentName, String environment, boolean isRead) {
   SqlSessionFactory sqlSessionFactory =
       this.getSqlSessionFactory(componentName, environment, isRead);
   long start = System.currentTimeMillis();
   SqlSession session = sqlSessionFactory.openSession(true);
   long end = System.currentTimeMillis();
   if (end - start > 100) {
     LOG.warn("open sql session:" + environment + " " + (end - start) + " millionSeconds");
   }
   return session;
 }
예제 #14
0
 private void getSqlSession() {
   SqlSessionFactory sqlSessionFactory = null;
   String resource = "mybatis.xml";
   InputStream inputStream;
   try {
     inputStream = Resources.getResourceAsStream(resource);
     sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   } catch (IOException e) {
     e.printStackTrace();
   }
   this.session = sqlSessionFactory.openSession();
 }
예제 #15
0
  /**
   * Returns the list of all Contact instances from the database.
   *
   * @return the list of all Contact instances from the database.
   */
  @SuppressWarnings("unchecked")
  public List<Blog> select() {

    SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();

    try {
      List<Blog> list = session.selectList("Blog.selectBlog");
      return list;
    } finally {
      session.close();
    }
  }
예제 #16
0
  private SqlSessionFactory getSqlSessionFactory(
      String componentName, String environment, boolean isRead) {
    String ibatisConfigFile = componentName + IBATIS_CONFIG_SUFFIX;
    String ibatisConfigProperties = componentName + IBATIS_PROPERTIES_SUFFIX;
    // use componentName + "::" + environment as the key in void that environment conflict in the
    // ibatis runtime
    String environmentKey = componentName + "::" + environment;

    Map<String, SqlSessionFactory> tempSqlSessionFactoryMap = sqlSessionFactoryMap;

    if (!tempSqlSessionFactoryMap.containsKey(environmentKey)) {
      synchronized (LOCK) {
        if (!tempSqlSessionFactoryMap.containsKey(environmentKey)) {
          try {
            LOG.info(String.format("build datasource:%s", environmentKey));
            long start = System.currentTimeMillis();
            org.apache.ibatis.session.SqlSessionFactoryBuilder builder =
                new org.apache.ibatis.session.SqlSessionFactoryBuilder();
            reader = Resources.getResourceAsReader(ibatisConfigFile);
            Configuration configuration =
                ConfigurationManager.getInstance().getByFileName(ibatisConfigProperties);
            SqlSessionFactory factory =
                builder.build(reader, environment, configuration.toProperties());
            LOG.info(
                "Init database connection pool "
                    + factory.getConfiguration().getVariables().toString());
            tempSqlSessionFactoryMap.put(environmentKey, factory);

            long end = System.currentTimeMillis();
            if (end - start > 1000) {
              LOG.info(
                  String.format("build datasource %s cost %d ms", environmentKey, (end - start)));
            }
            return factory;
          } catch (Exception e) {
            e.printStackTrace();
            LOG.error(
                "build environment error " + environmentKey + " with error " + e.getMessage());
            return null;
          } finally {
            try {
              reader.close();
            } catch (IOException e) {
              LOG.error(e.getMessage());
            }
          }
        }
      }
    }
    return tempSqlSessionFactoryMap.get(environmentKey);
  }
예제 #17
0
  public static void main(String[] args) throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    //		UserInfo userInfo = sqlSessionFactory.openSession().selectOne(
    //				"UserInfo.getUserInfo", 11);
    //
    //		System.out.println(userInfo.getId());
    //		sqlSessionFactory.getConfiguration().addMapper(UserInfoMapper.class);

    UserInfoMapper mapper = sqlSessionFactory.openSession().getMapper(UserInfoMapper.class);
    System.out.println(mapper.getUserInfo(1).getUsername());
  }
예제 #18
0
 public static void main(String[] arg) {
   try {
     InputStream rd =
         Resources.getResourceAsStream(
             "src/main/resources/dongfy/learn/mybatis/config/mybatis-configuration.xml");
     SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(rd);
     SqlSession sqlSession = ssf.openSession();
     AppUser appUser = sqlSession.selectOne("selectAppUserByID");
     System.out.print(appUser.getCreatetime());
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
   }
 }
예제 #19
0
  public static void main(String[] args) {
    // mybatis的配置文件
    String resource = "config.xml";
    // 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
    // InputStream is = App.class.getClassLoader().getResourceAsStream(resource);
    // 构建sqlSession的工厂
    Reader reader = null;
    try {
      reader = Resources.getResourceAsReader(resource);
    } catch (IOException e) {

    }
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    // 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
    // Reader reader = Resources.getResourceAsReader(resource);
    // 构建sqlSession的工厂
    // SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    // 创建能执行映射文件中sql的sqlSession
    SqlSession session = sessionFactory.openSession();

    /**
     * 映射sql的标识字符串, me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
     * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
     */
    String statement = "me.gacl.mapping.userMapper.getUser"; // 映射sql的标识字符串
    // 执行查询返回一个唯一user对象的sql
    // User user = session.selectOne(statement, 3234);
    IUserOperation userOperation = session.getMapper(IUserOperation.class);
    User user = userOperation.getUser(3);
    List<User> users = userOperation.selectUsers();
    for (User u : users) {
      System.out.println(u);
    }

    User newUser = new User();
    newUser.setName("tulianghui");
    newUser.setId(7968);
    userOperation.addUser(newUser);
    newUser.setId(3);
    newUser.setName("xxx");
    userOperation.updateUser(newUser);
    userOperation.deleteUser(newUser);
    List<Book> books = userOperation.getUserBooks(3234);
    for (Book book : books) {
      System.out.println(book.getBookname() + book.getUser().getName());
    }
    session.commit();
    session.close();
  }
예제 #20
0
  /**
   * Returns the list of all Contact instances from the database.
   *
   * @return the list of all Contact instances from the database.
   */
  public List<Blog> selectAnnotations() {

    SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();

    try {

      BlogMapper mapper = session.getMapper(BlogMapper.class);
      List<Blog> list = mapper.selectAllBlogs();

      return list;
    } finally {
      session.close();
    }
  }
예제 #21
0
 /** 读取转换数据 */
 public static List<TransUidInfo> getTransUidInfos(String tablename, String identify) {
   TransUidSelectParams transUidSelectParams = new TransUidSelectParams(tablename, identify);
   try (SqlSession sqlSession = sqlSessionFactory.openSession(); ) {
     TransUidDao transUidDao = sqlSession.getMapper(TransUidDao.class);
     return transUidDao.getTransUidInfos(transUidSelectParams);
   }
 }
예제 #22
0
 @Override
 public T queryOne(T t) {
   SqlSession sqlSession = sqlSessionFactory.openSession(false);
   t = sqlSession.selectOne(namespace.concat("queryOne"), t);
   sqlSession.close();
   return t; // 返回类型为T
 }
예제 #23
0
 /** 测试新增 */
 @Test
 public void insert() {
   SqlSession session = null;
   try {
     CalculationRecordModel model = new CalculationRecordModel();
     model.setCreatedTime(new Date());
     model.setCurrentNumber(1.0);
     model.setPreNumber(2.0);
     model.setOperator("*");
     model.setResult(3.0);
     model.setStatus(1);
     model.setMacAddress("pc1");
     session = sessionFactory.openSession();
     CalculationDao calculationDao = session.getMapper(CalculationDao.class);
     // calculationDao.insertCalculationRecord(model);
     List<Integer> Ids = new ArrayList<Integer>();
     Ids.add(3);
     Ids.add(4);
     // int[] Ids = {1,2};
     List<CalculationRecordModel> modelList = calculationDao.getCalculationRecordByID(Ids);
     for (CalculationRecordModel calculationRecordModel : modelList) {
       System.out.println(calculationRecordModel);
     }
     session.commit();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     session.close();
   }
 }
예제 #24
0
파일: EntityDao.java 프로젝트: kelink/spms
  @Override
  public <T> void batchDelete(String mapperId, List<T> t) {
    SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, true);

    session.delete(mapperId, t);
    session.commit();
  }
예제 #25
0
  public static void main(String[] args) throws IOException {

    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

    InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis_config.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();

    MemberMapper mapper = session.getMapper(MemberMapper.class);
    List<Member> list = mapper.selectAll();

    for (Member m : list) System.out.println(m.getId() + " " + m.getEmail());

    Member m = mapper.selectById(1001);
    System.out.println(m.getId() + " " + m.getEmail());
  }
예제 #26
0
 @Test
 public void testDB() {
   Map<String, Object> param = new HashMap<String, Object>();
   session = sqlSessionFactory.openSession();
   UserMapper userMapper = session.getMapper(UserMapper.class);
   System.out.println(userMapper.list(param));
 }
예제 #27
0
 @Test
 public void testInserUser() throws ParseException {
   // 通过sqlSessionFactory创建sqlSession
   SqlSession sqlSession = sqlSessionFactory.openSession();
   // 通过sqlSession操作数据库
   // 插入对象
   User user = new User();
   user.setUsername("李泽贤");
   user.setAddress("广西南宁");
   user.setSex("男");
   SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
   Date birthday = date.parse("1993-05-06");
   user.setBirthday(birthday);
   try {
     // 第一个参数:statement位置,等于namespace+statement的id
     // 第二个参数:传入的参数
     sqlSession.insert("test.inserUser", user);
     sqlSession.commit();
   } catch (Exception e) {
     // TODO: handle exception
     e.printStackTrace();
   } finally {
     sqlSession.close();
   }
   System.out.println("返回的主键" + user.getId());
 }
예제 #28
0
 @SuppressWarnings("unchecked")
 @Override
 public List<UsuarioDTO> buscarUsuarioPaginados(UsuarioDTO usuario, Integer inicio, Integer tamano)
     throws Exception {
   SqlSession sesion = sqlMapper.openSession();
   List<UsuarioDTO> lstUsuario = new ArrayList<UsuarioDTO>();
   try {
     if (usuario == null) {
       UsuarioDTO provee = new UsuarioDTO();
       provee.setInicio(inicio);
       provee.setTamano(tamano);
       lstUsuario =
           (List<UsuarioDTO>) sesion.selectList("usuario.SQL_listaUsuarioPaginados", provee);
     } else {
       if (!usuario.getNom_usuario().isEmpty()) {
         usuario.setNom_usuario("%" + usuario.getNom_usuario() + "%");
         usuario.setInicio(inicio);
         usuario.setTamano(tamano);
         lstUsuario =
             (List<UsuarioDTO>)
                 sesion.selectList("usuario.SQL_listaUsuarioNom_usuarioPaginados", usuario);
       }
     }
   } finally {
     sesion.close();
   }
   return lstUsuario;
 }
예제 #29
0
  public int update(String title, String content, Date startDate, Date endDate, String tag, int no)
      throws Exception {
    System.out.println(title + " - " + content + " - " + startDate + " - " + no);

    SqlSession sqlSession = sqlSessionFactory.openSession();

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("title", title);
    params.put("content", content);
    params.put("startDate", startDate);
    params.put("endDate", endDate);
    params.put("tag", tag);
    params.put("no", no);

    try {
      int rsn = sqlSession.update("net.bitacademy.java41.dao.ProjectMapper.update", params);
      sqlSession.commit();
      return rsn;

    } catch (Exception e) {
      throw e;

    } finally {
      try {
        sqlSession.close();
      } catch (Exception e) {
      }
    }
  }
예제 #30
0
파일: EntityDao.java 프로젝트: kelink/spms
  @Override
  public <T> void batchAdd(String mapperId, List<T> t) {
    SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);

    session.insert(mapperId, t);
    session.commit();
  }