JPA新特性

通过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的功能。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值