通过AttributeConverter实现实体类的属性映射:
public class ContactInfoTypeConverter implements AttributeConverter<ContactInfoType, String> {
@Override
public String convertToDatabaseColumn(ContactInfoType type) {
switch (type) {
case PRIVATE:
return "P";
case BUSINESS:
return "B";
default:
throw new IllegalArgumentException("ContactInfoType ["+ type.name() + "] not supported.");
}
}
@Override
public ContactInfoType convertToEntityAttribute(String dbType) {
switch (dbType) {
case "P":
return ContactInfoType.PRIVATE;
case "B":
return ContactInfoType.BUSINESS;
default:
throw new IllegalArgumentException("ContactInfoType [" + dbType + "] not supported.");
}
}
}
public class ContactInfoTypeCdiConverter implements AttributeConverter<ContactInfoType, String> {
@Inject
ContactInfoTypeHelper conversionHelper;
@Override
public String convertToDatabaseColumn(ContactInfoType type) {
return conversionHelper.convertToString(type);
}
@Override
public ContactInfoType convertToEntityAttribute(String dbType) {
return conversionHelper.convertToContactInfoType(dbType);
}
}
获取Stream:
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaStreamTest {
@Autowired
EntityManager entityManager;
@Autowired
MenuRepository menuRepository;
@Test
public void testJpaStream() {
TypedQuery<Menu> q = entityManager.createQuery("SELECT m FROM Menu m", Menu.class);
Stream<Menu> menuStream = q.getResultList().stream();
menuStream.filter(menu -> menu.getType().equals(MenuType.MENU)).forEach(menu -> System.out.println(menu.getAlias()));
}
}
值得一提的是有些场景用SQL查询做比使用Stream API更高效。从Stream中过滤一些元素,在某个节点取消处理过程,或者改变元素的顺序,可能比较有吸引力。但是,用SQL语句来做这些事情是一种更好的实践。数据库对这些类型的操作做了高度优化,而且比你用Java实现的任何方法都更高效。最重要的是,你通常很可能会减少需要从数据库传送到应用程序的数据量,将它们映射成实体,然后存储在内存中。因此,始终确保在查询中执行尽可能多的操作,并尽可能充分地利用SQL的功能。