mybatis简单示例

mybatis简单示例

创建mybatis配置文件:mybatis.xml























创建数据库信息文件db.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=system
pass=123456

创建数据库操作接口类SwictchCfgDAO

public interface SwictchCfgDAO {
/**
* 根据参数查询表数据
* @param switchId
* @return
* @throws Exception
*/
public SwitchCfg getSwitchById(String switchId)throws Exception;
}

创建接口类映射文件switch.xml




创建实体类对象SwitchCfg

public class SwitchCfg {
String switch_ID;
String switch_Name;
String switch_Flag;
String switch_Content;
String switch_Class;
String ordinal;
String switch_Class_Code;
String class_Ordinal;

public String getSwitch_ID() {
return switch_ID;
}

public void setSwitch_ID(String switch_D) {
this.switch_ID = switch_D;
}

public String getSwitch_Name() {
return switch_Name;
}

public void setSwitch_Name(String switch_Name) {
this.switch_Name = switch_Name;
}

public String getSwitch_Flag() {
return switch_Flag;
}

public void setSwitch_Flag(String switch_Flag) {
this.switch_Flag = switch_Flag;
}

public String getSwitch_Content() {
return switch_Content;
}

public void setSwitch_Content(String switch_Content) {
this.switch_Content = switch_Content;
}

public String getSwitch_Class() {
return switch_Class;
}

public void setSwitch_Class(String switch_Class) {
this.switch_Class = switch_Class;
}

public String getOrdinal() {
return ordinal;
}

public void setOrdinal(String ordinal) {
this.ordinal = ordinal;
}

public String getSwitch_Class_Code() {
return switch_Class_Code;
}

public void setSwitch_Class_Code(String switch_Class_Code) {
this.switch_Class_Code = switch_Class_Code;
}

public String getClass_Ordinal() {
return class_Ordinal;
}

public void setClass_Ordinal(String class_Ordinal) {
this.class_Ordinal = class_Ordinal;
}
/**
* 重写toString方法为了测试显示
* @return
*/
@Override
public String toString() {
return switch_ID+switch_Name;
}
}

编写测试类MyBatisTest

public class MyBatisTest {
public static void main(String[] args) {
String resource = "mybatis.xml";
Reader reader = null;
SqlSession session = null;
try {
reader = Resources.getResourceAsReader(resource);
//初始化工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//获取数据库操作对象
session= sessionFactory.openSession();
SwictchCfgDAO swictchCfgDAO = session.getMapper(SwictchCfgDAO.class);
SwitchCfg switchCfg = swictchCfgDAO.getSwitchById("inp_sel_023");
System.out.println(switchCfg.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if(session!=null){
session.close();
}
}
}
}

测试结果

posted @ 2018-11-10 14:17  倪启根  阅读(239)  评论(0)    收藏  举报