本科专业“软件工程”和“计算机辅助软件工程科学与技术”的区别是什么

匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。laravel查询构造器中别名的问题
laravel查询构造器中别名的问题
laravel技术篇
Laravel框架对数据库的封装是比较完善的,用起来也比较方便。但之前有一个问题一直困扰着我,就是利用laravel作查询时。如果想给表名或是字段名起别名是比较麻烦的事。但翻阅它的文档不难发现,它提供了一个DB::raw()的方法给我们,利用这个方法,我们就可以轻松的实现对表的重命名。
问题还原:
一般的写法:DB::table('users')-&select('id','username')-&get();
这样写是一点问题没有的。
加别名的写法:
这样写也不会产生错误
我们尝试另一咱写法:&get();
这样写就报错了,但这种写法我们又是不能避免的,如我们要表users表进行自连接时,就必须要用到别名加点的方式去得到字段。这样问题就来了。
不着急,我们先看看这句话输出的SQL语句是什么样的。我们用laravel提供的一个方法toSql()去得到SQL语句
DB::table('usersas table1')-&select('table1.id')-&toSql();
结果为:select`ykttb_table1`.`id` from `ykttb_users` as `table1`
我们发现写table1.id时,laravel框架自动给我们加上了表前缀,很显然,这样的SQL语句得不到我们要的结果。
最后的尝试:DB::table('users astable1')-&select(DB::raw('table1.id'))-&get();
这样写就没错了,用上面的方法来输出SQL语句:select table1.id from `ykttb_users` as `table1`
这就是我们想要执行的SQL语句。
总结:在laravel中,给表起别名,直接写就可以;但在select语句中要用到表的别名来得到字段,我们就要在外面套一层DB::raw(),
我的热门文章
即使是一小步也想与你分享请教Laravel多个条件的关联查询问题 -php教程-PHP中文网QQ群微信公众号请教Laravel多个条件的关联查询问题 Laravel多个条件的关联查询问题 :表 order 订单表:id 自增IDorder_id 订单号paid_date 支付时间表 order_product 订单产品表:id 自增IDfk_order_id 订单号,外键product_name 名称product_number 编号quantity 数量 表关系: order - 1:n - order_product 需求: 通过 Laravel Eloquent ORM 实现以下原生 SQL:select * from order as A inner join order_product as B on A.order_id=B.fk_order_id
where (A.paid_date between '' and '') and B.product_name like '%Apple iPhone%'手册看了几次,尝试着做,但目前只通过 whereHas 实现 B.product_name like 这部分的条件,当两个表都存在条件的时候,实在是做不出来。望 Laravel 前辈们指点一下,谢谢! PS. 补充:目前是针对列表页做筛选检索,存在 paginate 的需求。以上就是请教Laravel多个条件的关联查询问题 的内容,更多相关内容请关注PHP中文网()!0点赞收藏分享:&猜你喜欢 $time = ['', ''];
$response = \DB::table(....)->join(....)
$response->where(function($query) use($time){
$query->whereBetween('A.paid_date',$time );
})->where('B.首页上一页下一页尾页2345678910
:独家原创,永久免费的PHP教程,PHP技术学习阵地!Copyright
All Rights Reserved | 皖B2-QQ群:关注微信公众号今天做项目& 碰到一个问题:现有 Order Ticket Jingdian 三个实体类 ,分别对应 t_order,t_ticket,t_jingdian三张表
类Order里面有ticketId
类Ticket里面有List&Jingdian&
类Jingdian里面有 memo
请问一下,通过 Jingdian里面的 memo 属性来查询订单的HQL语句应该怎么写?
因为Ticket里面没有memo字段属性,还请知道的大神指点一二。
回答: Hibernate一对多对的查询HQL问题
这样行不?
select order.*,ticket.*,jingdian.* from t_order order left join t_ticket ticket on order.ticket_id = ticket.ticket_id left join
t_jingdian on jingdian.jingdian_id
= ticket.jingdian_id where jingdian.memo = ?
Q 描述:主要是实体一对多的关系,不希望懒加载,需要急加载。配置完后,查询时报sql语法错误,将sql语句拷到mysql中执行,把{}去除,花括号其实就是映射的数据库字段,执行成功。仔细看了一下错误,象是hibernate执行时没有把花括号{}给替换成数据库字段名称,直接带着花括号查询了,当然会报错,为什么会出现这种问题,没有找到原因。有没有朋友知道的?
po类:一对多的关系,Jpa配置如下(单向关联)
&&&&&
@SuppressWarnings("serial")
@Table(name = "mplan_notice")
public class MplanNotice implements java.io.Serializable {
private Set&MplanNoticePosition& mplanNoticePositions =
new HashSet&MplanNoticePosition&(0);
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name = "{notice_id}")
@Cascade(value = { CascadeType.SAVE_UPDATE })
public Set&MplanNoticePosition& getMplanNoticePositions() {
return mplanNoticeP
public void setMplanNoticePositions(
Set&MplanNoticePosition& mplanNoticePositions) {
this.mplanNoticePositions = mplanNoticeP
@SuppressWarnings("serial")
@Table(name = "mplan_notice_position")
public class MplanNoticePosition implements java.io.Serializable {
private String noticeId;
@Column(name = "id" )
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
public String getId() {
public void setId(String id) {
//定义外键名称
@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name="{position_id}")
public Position getPosition() {
public void setPosition(Position position) {
this.position =
@Column(name = "notice_id" )
public String getNoticeId() {
return noticeId;
public void setNoticeId(String noticeId) {
this.noticeId = noticeId;
操作:采用hibernateTemplate.get(entityclass,id)获取MplanNotice对象,并且设置为fetch.eager,急查询,能直接把MplanNotice的Set集合获取。
错误:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not load an entity: [com.thinkwin.mlcm.mplan.po.MplanNotice#1]; SQL [select mplannotic0_.id as id38_10_, mplannotic0_.busstate as busstate38_10_, mplannotic0_.memo as memo38_10_, mplannotic0_.operate_time as operate4_38_10_, mplannotic0_.operate_user as operate8_38_10_, mplannotic0_.plan_month as plan5_38_10_, mplannotic0_.plan_quarter as plan6_38_10_, mplannotic0_.plan_year as plan7_38_10_, mplannotic0_.plantype as plantype38_10_, mplannotic1_.{notice_id} as column4_12_, mplannotic1_.id as id12_, mplannotic1_.id as id39_0_, mplannotic1_.{job_id} as column3_39_0_, mplannotic1_.notice_id as notice2_39_0_, job2_.id as id71_1_, job2_.create_by as create2_71_1_, job2_.create_time as create3_71_1_, job2_.description as descript4_71_1_, job2_.job_name as job5_71_1_, job2_.org_id as org8_71_1_, job2_.position_id as position9_71_1_, job2_.update_by as update6_71_1_, job2_.update_time as update7_71_1_, mplannotic3_.{notice_id} as column4_13_, mplannotic3_.id as id13_, mplannotic3_.id as id40_2_, mplannotic3_.notice_id as notice2_40_2_, mplannotic3_.{person_id} as column3_40_2_, person4_.id as id73_3_, person4_.person_name as person2_73_3_, person4_.sex as sex73_3_, mplannotic5_.{notice_id} as column4_14_, mplannotic5_.id as id14_, mplannotic5_.id as id41_4_, mplannotic5_.notice_id as notice2_41_4_, mplannotic5_.{position_id} as column3_41_4_, position6_.position_id as position1_76_5_, position6_.create_by as create2_76_5_, position6_.create_time as create3_76_5_, position6_.description as descript4_76_5_, position6_.forder as forder76_5_, position6_.parent_position_id as parent9_76_5_, position6_.position_name as position6_76_5_, position6_.update_by as update7_76_5_, position6_.update_time as update8_76_5_, user7_.id as id87_6_, user7_.create_by as create2_87_6_, user7_.create_time as create3_87_6_, user7_.person_id as person9_87_6_, user7_.pwd as pwd87_6_, user7_.status as status87_6_, user7_.update_by as update6_87_6_, user7_.update_time as update7_87_6_, user7_.user_name as user8_87_6_, person8_.id as id73_7_, person8_.person_name as person2_73_7_, person8_.sex as sex73_7_, dictionary9_.DICT_ID as DICT1_94_8_, dictionary9_.DICT_NAME as DICT2_94_8_, dictionary9_.dict_type_id as dict5_94_8_, dictionary9_.DICT_CODE as DICT3_94_8_, dictionary9_.forder as forder94_8_, dictionary10_.DICT_TYPE_ID as DICT1_95_9_, dictionary10_.DICT_TYPE_CODE as DICT2_95_9_, dictionary10_.DICT_TYPE_NAME as DICT3_95_9_, dictionary10_.module_id as module5_95_9_, dictionary10_.state as state95_9_ from mplan_notice mplannotic0_ left outer join mplan_notice_job mplannotic1_ on mplannotic0_.id=mplannotic1_.{notice_id} left outer join org_job job2_ on mplannotic1_.{job_id}=job2_.id left outer join mplan_notice_person mplannotic3_ on mplannotic0_.id=mplannotic3_.{notice_id} left outer join org_person person4_ on mplannotic3_.{person_id}=person4_.id left outer join mplan_notice_position mplannotic5_ on mplannotic0_.id=mplannotic5_.{notice_id} left outer join org_position position6_ on mplannotic5_.{position_id}=position6_.position_id left outer join scy_user user7_ on mplannotic0_.operate_user=user7_.id left outer join org_person person8_ on user7_.person_id=person8_.id left outer join res_dictionary dictionary9_ on mplannotic0_.plantype=dictionary9_.DICT_ID left outer join res_dictionary_type dictionary10_ on dictionary9_.dict_type_id=dictionary10_.DICT_TYPE_ID where mplannotic0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not load an entity: [com.thinkwin.mlcm.mplan.po.MplanNotice#1]
问题补充:kidding87 写道那就把注解写到属性上试试
刚才试过了,还是同样的问题,跟踪hibernate源代码查到EntityPersiters生成loaders时,生成load sql涉及到一对多的关联属性就都被大花括号括起来了,直到最后执行sql语句的时候,还是没弄清楚根源是什么,问题也没解决
问题补充:kidding87 写道你把import都换成hibernate包的呢?
hibernate包只有这些吧:
import org.hibernate.annotations.C
import org.hibernate.annotations.CascadeT
import org.hibernate.annotations.E
import org.hibernate.annotations.GenericG
import org.hibernate.annotations.T
onetomany manytoone 的用的还是jpa ,不行。
问题补充:kidding87 写道在不行,在
CascadeType.PERSIST 后面加上CascadeType.merge
更改后的局部代码:
private Set&MplanNoticePerson& mplanNoticePersons = new HashSet&MplanNoticePerson&(0);
@OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST,CascadeType.MERGE})
@JoinColumn(name = "{notice_id}")
public Set&MplanNoticePerson& getMplanNoticePersons() {
return mplanNoticeP
出来的SQL还是那样,报错信息(全):
org.springframework.dao.InvalidDataAccessResourceUsageException: could not load an entity: [com.thinkwin.mlcm.mplan.po.MplanNotice#1]; SQL [select mplannotic0_.id as id38_8_, mplannotic0_.busstate as busstate38_8_, mplannotic0_.memo as memo38_8_, mplannotic0_.operate_time as operate4_38_8_, mplannotic0_.operate_user as operate8_38_8_, mplannotic0_.plan_month as plan5_38_8_, mplannotic0_.plan_quarter as plan6_38_8_, mplannotic0_.plan_year as plan7_38_8_, mplannotic0_.plantype as plantype38_8_, mplannotic1_.{notice_id} as column4_10_, mplannotic1_.id as id10_, mplannotic1_.id as id40_0_, mplannotic1_.notice_id as notice2_40_0_, mplannotic1_.{person_id} as column3_40_0_, person2_.id as id73_1_, person2_.person_name as person2_73_1_, person2_.sex as sex73_1_, mplannotic3_.{notice_id} as column4_11_, mplannotic3_.id as id11_, mplannotic3_.id as id41_2_, mplannotic3_.notice_id as notice2_41_2_, mplannotic3_.{position_id} as column3_41_2_, position4_.position_id as position1_76_3_, position4_.create_by as create2_76_3_, position4_.create_time as create3_76_3_, position4_.description as descript4_76_3_, position4_.forder as forder76_3_, position4_.parent_position_id as parent9_76_3_, position4_.position_name as position6_76_3_, position4_.update_by as update7_76_3_, position4_.update_time as update8_76_3_, user5_.id as id87_4_, user5_.create_by as create2_87_4_, user5_.create_time as create3_87_4_, user5_.person_id as person9_87_4_, user5_.pwd as pwd87_4_, user5_.status as status87_4_, user5_.update_by as update6_87_4_, user5_.update_time as update7_87_4_, user5_.user_name as user8_87_4_, person6_.id as id73_5_, person6_.person_name as person2_73_5_, person6_.sex as sex73_5_, dictionary7_.DICT_ID as DICT1_94_6_, dictionary7_.DICT_NAME as DICT2_94_6_, dictionary7_.dict_type_id as dict5_94_6_, dictionary7_.DICT_CODE as DICT3_94_6_, dictionary7_.forder as forder94_6_, dictionary8_.DICT_TYPE_ID as DICT1_95_7_, dictionary8_.DICT_TYPE_CODE as DICT2_95_7_, dictionary8_.DICT_TYPE_NAME as DICT3_95_7_, dictionary8_.module_id as module5_95_7_, dictionary8_.state as state95_7_ from mplan_notice mplannotic0_ left outer join mplan_notice_person mplannotic1_ on mplannotic0_.id=mplannotic1_.{notice_id} left outer join org_person person2_ on mplannotic1_.{person_id}=person2_.id left outer join mplan_notice_position mplannotic3_ on mplannotic0_.id=mplannotic3_.{notice_id} left outer join org_position position4_ on mplannotic3_.{position_id}=position4_.position_id left outer join scy_user user5_ on mplannotic0_.operate_user=user5_.id left outer join org_person person6_ on user5_.person_id=person6_.id left outer join res_dictionary dictionary7_ on mplannotic0_.plantype=dictionary7_.DICT_ID left outer join res_dictionary_type dictionary8_ on dictionary7_.dict_type_id=dictionary8_.DICT_TYPE_ID where mplannotic0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not load an entity: [com.thinkwin.mlcm.mplan.po.MplanNotice#1]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:512)
at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:506)
at com.thinkwin.framework.core.base.dao.impl.BaseGenericDao.get(BaseGenericDao.java:275)
at com.thinkwin.mlcm.mplan.service.impl.MplanNoticeServiceImpl.findById(MplanNoticeServiceImpl.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy49.findById(Unknown Source)
at com.thinkwin.mlcm.mplan.service.IMplanNoticeServiceTest.testFindById(IMplanNoticeServiceTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.thinkwin.mlcm.mplan.po.MplanNotice#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1895)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:71)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:65)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3072)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:434)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:415)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:165)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:223)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:126)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:905)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:842)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:835)
at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:519)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
... 46 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL check the manual that corresponds to your MySQL server version for the right syntax to use near 'as column4_10_, mplannotic1_.id as id10_, mplannotic1_.id as id40_0_, mplannotic' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at mons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1808)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1881)
... 59 more
问题补充:kidding87 写道吃个饭,回来再试试
感谢!!
问题补充:kidding87 写道吃完了,回来就好像发现是什么问题了
{notice_id}
直接写notice_id
真的也,我好像也恍然大悟,真是个低级错误。谢谢大侠热心帮忙
A 吃完了,回来就好像发现是什么问题了
{notice_id}
直接写notice_id
Q 我的HQL语句如下:
def hql = new StringBuffer("SELECT ci FROM CarInfo ci join ci.drivers cds WHERE 1 = 1 ")
说明:
CarInfo : 车辆信息表
每辆车有多个驾驶员驾驶。也就是一辆车对应多个驾驶员(set),我想通过驾驶员查找所对应的车辆,条件语句如下:
if(params.driverName) hql && "AND cds.account.name LIKE '%${params.driverName}%' "
%${params.driverName}% 为页面获取的参数,即驾驶员姓名
VO如下:
CarInfo:
class CarInfo implements Comparable {
String carNo // 车牌编号
String brand // 品牌
String type
Date buyDate // 购买日期
Department dept // 所属部门
byte[] photo // 照片
String photoFileName
Integer onDuty // 特殊情况下,是否值班车辆
Integer flag // 标志
Users fgLeader // 分管领导
String memo
SortedSet drivers
SortedSet carCfgs
static hasMany = [drivers : DriverInfo, carCfgs: CarCfg]
其它略。。。
DriverInfo:
class DriverInfo implements Comparable {
Account account
String driverLicense // 驾照类型
Integer flag
String memo
SortedSet cars
static belongsTo = CarInfo
  static hasMany = [cars : CarInfo]
  其它略。。。
class Account {
Long account
String name
String sex
String pid
String dept
String sno
String flag
其它略。。。
使用的是Grails、Groovy
问题如下:
Caused by: org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException: Invalid query [SELECT ci FROM CarInfo ci join ci.drivers cds WHERE 1 = 1] for domain class [class CarInfo]
at CarInfoService.getList(CarInfoService.groovy:18)
at CarInfoService$$FastClassByCGLIB$$4df581d3.invoke(&generated&)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at CarInfoService$$EnhancerByCGLIB$$9ec3182d.getList(&generated&)
at CarInfoService$getList.call(Unknown Source)
at CarInfoController$_closure2.doCall(CarInfoController.groovy:21)
at CarInfoController$_closure2.doCall(CarInfoController.groovy)
改为left join 和 right join都不行!请教hibernate高手。
而另外一个放到子查询里的join就可以执行,代码如下:
def hql = new StringBuffer("FROM Account a WHERE TRIM(a.sno) IS NOT NULL ")
if(params.carNo) hql && "AND TRIM(a.id) IN (SELECT di.account.id FROM DriverInfo di join di.cars cs WHERE cs.carNo LIKE ('%${params.carNo}%')) "
A SELECT ci FROM CarInfo ci join ci.drivers cds WHERE 1 = 1
--》
from CarInfo ci left join fetch ci.drivers where 1=1
Q 首先祝大家端午节快乐。
最近学习hibernate,正用用他做博客,遇到个问题研究两天了也没研究出个什么。
hibernate一对多集合封装的问题,看文档一对多关联set配置中是主键和外键关联,
能不能设置这两个表中任意两个字段关联。google也没搜到(可能是我笨)。
不过有种方法通过HQL关联:
select tableone ,tablemany
from tableone tablemany where tableone.uuid=tablemany.uuid
可这样代表多的关系的那个表(tablemany)hibernate怎么给他封装成成集合?
如果我没说明白回复下我在补充。
研究东西总受折。程序员真不易啊。
秀下博客,快做完了就差这块了。
晕了,没人回答?
A 美工不错。还有一些细微的地方没有处理好
至于怎么封装成集合其实很简单
你都能把数据查出来,你还怕不知道怎么变成集合?
新建一个数据类。把符合要求的数据全部存储到这个类的实例里面,然后把多个这样的数据对象保存到集合里面,可以吗?
Q Hibernate一对多数据关联。指的是双向一对多数据关联一个盒子Box有多个卡片card
public class Box
@OneToMany(fetch=FetchType.LAZY )
@JoinColumn(name="BOX_ID")
@org.hibernate.annotations.Cascade(
value={org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@org.hibernate.annotations.IndexColumn(name="POS_NO", base=0)
private List&Card& cards = new ArrayList&Card&();
@Table(name="CARD")
public class Card
@ManyToOne
@JoinColumn(name="BOX_ID")
private Box box
@Column(name="POS_NO")
我如此注释映射是否存在问题?
从一个Box中在删除一个Card时报错!!!执行sql不对
public class Bus
public Box delandGet(Integer boxId, Integer delCardid){
Box bx = getHibernateTemplate().get( Box.class, boxId);
List&Card& cds =
bx.getCards();
Card del =
int di = -1;
for(int i=0; i&cds.size() ; i++){
Card c = cds.get(i);
if(c.id.equals(delCardid){
if(di != -1){
cds.remove(di);
del.setBox(null);
getHibernateTemplate().delete( del ) ;
删除始终不成功报错!!
Hibernate: update CARD set BOX_ID=null, POS_NO=null where BOX_ID=? and id=?
Hibernate: update CARD set BOX_ID=null, POS_NO=null where BOX_ID=? and id=?
问题补充:wzglovejava 写道把你的相关的错误信息贴出来呀,我想你的问题,应该出在你的代码上,
if(di != -1){
cds.remove(di);
del.setBox(null);
getHibernateTemplate().delete( del ) ;
这里的意思是,先将cds集合中的一个元素移除,再将移除元素映射的单个元素设置为空,最后再删除这个被移除的元素,是这样吧!感觉一下,这里有问题吗?
作者说明:hibernate update 更新语句明显不对
我的目标是在一个Box内删除一个card
card n:1 box 为什么hibernate先更新为null???
问题补充:WARN [http-8080-2] [org.hibernate.util.JDBCException[size=xx-small][/size]Reporter] :&org.hibernate.util.JDBCExceptionRe
porter.logExceptions(JDBCExceptionReporter.java:77)&
++ SQL Error: 0, SQLState: null
ERROR [http-8080-2] [org.hibernate.util.JDBCExceptionReporter] :&org.hibernate.util.JDBCExceptionR
eporter.logExceptions(JDBCExceptionReporter.java:78)&
++ failed batch
ERROR [http-8080-2] [org.hibernate.event.def.AbstractFlushingEventListener] :&org.hibernate.event.
def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:301)&
++ Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:1
03)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:92)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:87)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:222)
at org.hibernate.persister.collection.OneToManyPersister.doUpdateRows(OneToManyPersister.java:236
)
at org.hibernate.persister.collection.AbstractCollectionPersister.updateRows(AbstractCollectionPe
rsister.java:1519)
at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:55)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventL
istener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.springframework.orm.hibernate3.HibernateAccessor.flushIfNecessary(HibernateAccessor.java:3
90)
at org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor.postHandle(OpenSession
InViewInterceptor.java:181)
at org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter.postHandle(WebRequ
estHandlerInterceptorAdapter.java:61)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:886)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:2
90)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilte
r.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:2
35)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:58
1)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.BatchUpdateException: failed batch
at org.hsqldb.jdbc.jdbcStatement.executeBatch(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeBatch(Unknown Source)
at mons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
... 37 more
问题补充:wzglovejava 写道在HIbernate中删除一个附属对象有两种情况,第一种:并不会删除附属对象在数据库中的记录,只是将相应的关联字段进行修改,第二种:将附属对象数据删除。默认情况下应该是第一种伪删除,如果想要删除需要配置cascade="all-delete-orphan"吧,许久没用了,你试一下
@OneToMany(fetch=FetchType.LAZY )&&
&&& @JoinColumn(name="BOX_ID")&&
&&& @org.hibernate.annotations.Cascade(&&
&&&&&&& value={org.hibernate.annotations.CascadeType.SAVE_UPDATE,&&
&&&&&&&&&&&&&&& org.hibernate.annotations.CascadeType.DELETE_ORPHAN})&&&
&&& @org.hibernate.annotations.IndexColumn(name="POS_NO", base=0)&&
&&& private List&Card& cards = new ArrayList&Card&();&
org.hibernate.annotations.CascadeType.DELETE_ORPHAN
上面一条对否清指教
getHibernateTemplate().delete( del ) ; //删除
问题补充:wzglovejava 写道实践出真知。要学会自己去尝试。要相信在很多次失败之后总有一次会成功!!!
变通一下也行但 我想搞明白:一对多采用List映射 如何处理!!
我用List映射主要是为保证Box的Card顺序
如:del时insert时不用编程维护顺序,看大家有何办法?
在此多谢了!!
问题补充:zhangkaitao 写道你这是单向一对多,所以@OneToMany(fetch=FetchType.LAZY,mappedBy="box")。
@JoinColumn(name="BOX_ID",nullable=false)应该就好了& ,因为如果允许为null的话,hibernate就更新为null,也是级联啊,如果不允许为null,hibernate知道我现在应该删除他,试试吧
我尝试:
& @JoinColumn(name="BOX_ID" ,updatable=false)
@JoinColumn(name="BOX_ID" ,nullable=false)
都不行!!难道只有将db字段设为可为null
问题补充:引用
private List&Card& cards = new ArrayList&Card&();&
在一方加上@JoinColumn(name="BOX_ID" ,updatable=false)
这样虽然 不报错 但也不能更新关联List下标
问题补充:回复 zhangkaitao:
谢谢你的代码!!
session.delete(item2);这段代码&
意思是:只是删除多方, 一方的关联集合不移动那不造成中间缺位;
删除第三个元素要后面第4,5补上,看来要程序来补位;
你没映射position,如何补位?
我再试一试!!
问题补充:
@ManyToOne
@JoinColumn(name="BOX_ID",updatable = false, insertable = false)
private Box box
我在多对一 设置updatable = false, insertable = false
在一对多Box 的关联列表cards 末尾插入Card 报错!!!
引用
Hibernate: insert into CARD (BOX_ID, TEXT_CONTENT, IMAGE_URL, POS_NO, STYLE_ID, id) values (?, ?, ?, ?, ?, ?)
Hibernate: update CARD set BOX_ID=null, POS_NO=null where BOX_ID=? and id=?
WARN [http-8080-2] [org.hibernate.util.JDBCExceptionReporter] :&org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReport
er.java:77)&
++ SQL Error: 0, SQLState: null
ERROR [http-8080-2] [org.hibernate.util.JDBCExceptionReporter] :&org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionRepor
ter.java:78)&
++ failed batch
ERROR [http-8080-2] [org.hibernate.event.def.AbstractFlushingEventListener] :&org.hibernate.event.def.AbstractFlushingEventListener.perfor
mExecutions(AbstractFlushingEventListener.java:301)&
++ Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
我不设置updatable = false, insertable = false
成功在Box 的关联列表cards 末尾插入C
但在Box 的关联中间位置(第2个)插入 Card 报错!!
我是不是不能映射POS_NO 字段??
奇怪?hibernate总是更新NULL(插入时)
盼大家给于解答??
public class Item3 {
@GeneratedValue(strategy = GenerationType.AUTO)
@OneToMany(fetch = FetchType.LAZY)
@Cascade(value = {CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN})
@JoinColumn(name = "item_id", nullable = false)
@org.hibernate.annotations.IndexColumn(name="position", base=0)
private List&Image3& images = new ArrayList&Image3&();
public List&Image3& getImages() {
public void setImages(List&Image3& images) {
this.images =
public void addImage(Image3 image) {
this.images.add(image);
image.setItem(this);
public class Image3 {
@GeneratedValue(strategy = GenerationType.AUTO)
@ManyToOne()
@JoinColumn(name = "item_id", nullable = false, updatable = false, insertable = false)
private Item3
@Column(name = "filename")
private String fileN
final Item3 item = new Item3();
item.setName("zzzz");
Image3 image = new Image3();
image.setFileName("aaa");
item.addImage(image);
this.hibernateTemplate.save(item);
System.out.println("=============================================");
this.hibernateTemplate.execute(new HibernateCallback&Void&() {
public Void doInHibernate(Session session) throws HibernateException, SQLException {
Item3 item2 = (Item3) session.get(Item3.class, item.getId());
session.delete(item2);
你按照这个改改吧,试一下
Q 先说说我的hql语句:
FROM Ciuser U WHERE 1=1 AND U.id.userId=?
hibernate对应的表是无主键,我传参的方式也是用‘?’代替的,而不是‘:参数名’。
通过hibernate的Query接口执行hql语句。
Query query = session.createQuery(hql);
query.setParameter(0,值);
return query.list();
代码运行大致是这样,但是执行完后是没查询到任何结果的。
后来我换成‘:参数名’的方式进行传参,但还是没有效果。
但是我换种方式,直接拼成字符串
FROM Ciuser U WHERE 1=1 AND U.id.userId='" + string对象 + "'
Query query = session.createQuery(hql);
return query.list();
以上拼字符串方式又是没问题的,不知道是什么原因,请各位指教!
我所使用的hibernate是3.3.1.GA spring是2.5.5。不知道和包有关系没有?
以前我使用JDBC也遇到过此种问题,当时没有重视。PreparedStatement的setParameter,也是没起作用,为什么呢?问题补充:我找到原因了,跟数据库字段类型有关系。
USER_ID这个字段,在数据库中是char(20),使用setParameter的话,就必须补空格20位定长才能查询出来,如果字段类型是varchar()就没问题。
但是char()的效率在varchar()之上,也不能因为程序的原因去修改数据库,何况USER_ID这个字段是会经常修改的。
如果这种问题,各位平时是怎么处理的。问题补充:我用的是oracle数据库。
我用char的原因是USER_ID这个字段值不是定长的,但是会经常修改,如果换成varchar的话后期查询效率肯定会大大降低的。
如何是这种情况大家怎么处理。问题补充:VARCHAR2虽然比CHAR节省空间,但是如果一个VARCHAR2列经常被修改,而且每次被修改的数据的长度不同,这会引起'行迁移' (Row Migration)现象,而这造成多余的I/O,是数据库设计和调整中要尽力避免的,在这种情况下用CHAR代替VARCHAR2会更好一些。
A VARCHAR2虽然比CHAR节省空间,但是如果一个VARCHAR2列经常被修改,而且每次被修改的数据的长度不同,这会引起'行迁移' (Row Migration)现象,而这造成多余的I/O,是数据库设计和调整中要尽力避免的,在这种情况下用CHAR代替VARCHAR2会更好一些。
虽然着是事实但是略有点危言耸听了,我们公司还在开发移动的应用呢,照样使用nvarchar完全没有一点问题!
Q 是这样的,鄙人对hibernate用的不是很多
关于hibernate多对多的时候
我们平时都是用set集合来
但是为什么不为hibernate像数据库那样,建立一个中间bean,来关联两边呢?
像下图这样
我的merchantInfo和MenuInfo是多对多的关系
写hql语句就这样写:
String hql = "from MenuInfo mi where mi.menuId in(select menuId from MerchantMenuInfo mmi where mmi.merchantId.merchantId=?) and mi.state=?";
请问这样写和写set集合的区别在哪里呢?哪个好呢?为什么没有见人用这样的方法呢?只是因为set方便么?
鄙人愚笨,还请各路同行兄弟指点一二。
A 使用Hibernate配置多对多关系,是可以创建中间实体来映射中间表的。具体你可以参见这篇博文& /admin/blogs/1129207
还有一般在集合表示时,使用List的较多,Set的用法主要是在无序和非重复的,因为Set不允许出现重复的元素,这时你就要定义好元素里的比较方法,判断什么情况下认为两个元素是相同的。写成集合的好处就是便于你在java代码中进行操作。
Q hibernate 一对多级联保存时,保存完一方和多方的对象后,怎又去更新多方的对象,为何?不明白,请教下问题补充:是级联保存的,hibernate会先保存一方对象,再保存多方对象,再又去更新多方的所有对象,我想知道Hibernate这样做的用意何在?
A 原因很简单,你问为什么会发出很多的update的SQL语句(如果你将SET标签添加上inverse="true"就不会有这样的情况,反转交给多的一方来维护),因为你现在是在让一的一方来维护关系:举个例子class和 student测试存储的方法中,
(1)你要先NEW出几个student对象
(2)创建一个SET集合,并添加student实体对象
(3)创建一个class对象,给这个实体的保留student SET集合的属性students赋值
(4)session.save(class);
你如果你要直接运行这个方法的话,会抛出transiont objecte excption 异常,因为在(1)中你的student对象为transient状态,要转化为persistent状态,要session.save(student1);....都要save;
----此时你会在输出端会看到hibernate发出了SQL insert语句,但是外键现在没有值
此时你的数据库student表中,外键字段class_id那列为里面都是NULL值,
接着执行,当session.save(class);
-----此时你才会看到hibernate发出了SQL update语句:
只要就是为了update student set class_id=".."where id="..",故存在几个student实体对象,就会发出几个update 。
通过上面可以看出它的缺点也就是:
第一:如果你将student表里的class_id字段设置为空,你就会无法保存数据;
第二:在class一方的一端会发出多余的update语句,你可以想象如果我要存1000个学生,那么你在一的一方维护关系,它就会发出1000条update。。。。。。
&&
一般不重要做,都是添上inverse=“true”反转给多的一方维护即可!
你可以在Eclipe 写测试方法设置断点来调试看下!
Q laravel多对多查询,不用join,用model,怎么查,愁哭了
/docs/4.2/eloquent#many-to-many
看下啊,支持多对多的,
貌似功能还挺强
Q goods商品表
int goodsid 自增,主键
varchar goodsName
varchar goodsAdress
relation中间表
int goods_id 主键 (无自增) 是goods表的外键
int stor_id 主键(无自增)是stor表的外键
int goodsNum
int price&&
stor 仓库表
int stor_id 主键,自增
varchar storName&
varchar storAdress
S2SH整合 这3个Pojo类和hibernate.hbm.xml是逆向自动生成的。
怎么查询出3个表中所有的数据同时传递到JSP页面。越详细越好!注重方法! 谢谢。。求指教 !!
问题补充:应该是4个pojo类 hibernate把联合主键的relation中间表分成了2个类 一个是goodsStorageId的类里面是2个表的Id
A goods
&& Set&relation&&& relationS
&&&&&&&&&&&&&&& goods
&&&&&&&&&&&&&&& stor
1、goods& 和 relationSet& 一对多
2、relation 包含 goods 和 stor
goods 和 stor 之间关系数据量大吗? 如果不大 可采用上边的级联
List&goods& 分页查即可(然后会级联抓取关系数据)
goods
relation
&&& goods
&&& stor
Map&goods, List&relation&& data
首先查goods 然后分页查relation}

我要回帖

更多关于 计算机科学软件工程 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信