JPA Hibernate 利用EntityManager 执行sql语句

分为三种情况:

1.更新,删除 语句

	public void test() {	//更新删除sql语句
		Query query = em.createNativeQuery("update user set age=10 where name = 'lsc'");
		/*Query query = em.createNativeQuery
		("insert into user (name,age,id) values ('zgc',10,99999999999988)");*/
		
		//Query query = em.createNativeQuery("delete from user where name='zgc'");
		
		int rows = query.executeUpdate();
		System.out.println(rows);
	}
	

2.查询语句(返回的是实体类型)

	public void test() {	//查询sql语句
		Query query = em.createNativeQuery("select * from user where name = 'lsc'",User.class);
		List list = query.getResultList();		
		System.out.println(list);
	}

3.复杂查询语句(返回结果不是实体类型,接收为Map类型)

	public void test() {	//查询sql语句
		Query query=
				em.createNativeQuery
				("select u.name,u.age,a.old from user u left join agetoold a on u.age = a.age");
		query.setFirstResult(0);	//设置从第几个结果开始
		query.setMaxResults(4);		//设置显示几个结果
		query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List> list = query.getResultList();
		System.out.println(list);
	}

 

你可能感兴趣的:(JPA Hibernate 利用EntityManager 执行sql语句)