IBatis: Discriminator Column Example Inheritance Mapping(Ibatis中的继承映射)
继承映射介绍-iBATIS supports inheritance hierarchies by using a special mapping called a discriminator. Using a discriminator you can determine the type of class to be instantiated based on a value in the database. The discriminator is a part of the ResultMap and works much like a switch statement.
?
问题:对于Manager和Developer来说,他们都是Employee类的子类,且都有自己特殊的属性,Manager有managerId和info属性,developer有developerId和project属性。在使用IBATIS查询一批Employee类时,如何通过自动映射通过判断Employee_type取得他们各自的属性?
?
?1、pojo beans

2、sqlMap
?3、test code
public class TestSqlMap { private static SqlMapClient sqlMapClient = null; @Before public void loadFile() { String resource = "sqlMap/sql-map-config.xml"; try { Reader reader = Resources.getResourceAsReader(resource); sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testSql(){ try { List<Employee> list = sqlMapClient.queryForList("getAllEmployees",null); for (Employee employee : list){ System.out.println(employee.toString()); } assertEquals(5, list.size()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }?
4、test result:
Employee ID = 1 Name = Kate Manager ID = 1 Info = info Kate
Employee ID = 4 Name = James Manager ID = 2 Info = info James
Employee ID = 5 Name = Susan Developer ID = 3 Project = web
Employee ID = 2 Name = Josh Developer ID = 1 Project = web
Employee ID = 3 Name = Peter Developer ID = 2 Project = desktop修改sqlMap,去掉managerMap的extends="resultEmployee"和developerMap的extends="resultEmployee"?:
Employee ID = 0 Name = null Manager ID = 1 Info = info Kate
Employee ID = 0 Name = null Manager ID = 2 Info = info James
Employee ID = 0 Name = null Developer ID = 3 Project = web
Employee ID = 0 Name = null Developer ID = 1 Project = web
Employee ID = 0 Name = null Developer ID = 2 Project = desktop5、在以上的例子中,子映射(sub map)对应这标准的结果映射,如果discriminator 找到了一个值去匹配subMap ,则父结果集的映射将失效,参加第四点的修改后的输出,除非子映射明确的扩展了父映射(extends)。
如果discriminator 找不到值去匹配subMap,则使用父结果映射:
Employee ID = 1 Name = Kate
1 楼 learnworld 2012-04-08 不错,很清晰!
Employee ID = 4 Name = James
Employee ID = 5 Name = Susan
Employee ID = 2 Name = Josh
Employee ID = 3 Name = Peter