com.albertzhe.mybatis_helloworld.service.AdminService.java Source code

Java tutorial

Introduction

Here is the source code for com.albertzhe.mybatis_helloworld.service.AdminService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.albertzhe.mybatis_helloworld.service;

import com.albertzhe.mybatis_helloworld.entity.Admin;
import com.albertzhe.mybatis_helloworld.mapper.AdminMapper;
import com.albertzhe.mybatis_helloworld.mapper.impl.AdminMapperImpl;
import com.albertzhe.mybatis_helloworld.util.SqlSessionUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 *
 * @author zhel
 */
public class AdminService {

    public Admin getAdmin(String key) {
        Long id = new Long(0);
        Admin admin = null;

        Pattern pattern = Pattern.compile("^[0-9]*$");
        Matcher matcher = pattern.matcher(key);
        if (!matcher.matches()) {
            return admin;
        } else {
            id = Long.valueOf(key);
        }

        //        AdminMapper adminMapper = new AdminMapperImpl(SqlSessionUtil.getInstance());
        //        admin = adminMapper.getAdminByID(id);
        /*
        2 MyBatis ??
        ?mybatis ? mapper ?
        */
        SqlSession sqlSession = SqlSessionUtil.getInstance().openSession();
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        admin = adminMapper.getAdminByID(id);

        return admin;
    }
}