I'm trying to have a Criteria query to have a restriction on an entity that isn't loaded.
My mapping is all done via one-to-many relations.
For example, I'm trying to get the following SQL query using criteria:
SELECT {msg.*} FROM Messages AS msg
WHERE msg.source_key IN
( SELECT ds.unique_key FROM Data_Sources AS ds " +
WHERE ds.source_type_key IN " +
( SELECT dst.unique_key FROM Data_Source_types AS dst " +
WHERE unique_name = 'RequiredName' ) )
Thus, I want to get Messages, with a restriction that is set on an entity that is not fetched by Hibernate. Currently, the best I could get is:
Criteria crit = session.createCriteria( Message.class )
.createAlias( "dataSource", "ds", CriteriaSpecification.INNER_JOIN )
.createAlias( "ds.sourceType", "type" )
.add( Restrictions.eq( "type.name", "HL7GatewayServer" ) )
However, this query also loads the dataSource and dataSourceType.
EDIT: My mapping:
MESSAGES:
@Entity
@Table(name="messages", schema="mySchema")
@SequenceGenerator(name="sequence",sequenceName="mySchema.local_key_sequence")
public class Message
{
@Id
@Column(name = "unique_key")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private long id;
@JoinColumn(name = "source_key")
@ManyToOne(targetEntity = DataSource.class, fetch = FetchType.LAZY)
private DataSource dataSource = null;
[...]
}
DATA_SOURCES:
@Entity
@Proxy(lazy = true)
@Table(name = "data_sources", schema = "mySchema")
@SequenceGenerator(name = "sequence", sequenceName = "mySchema.local_key_sequence")
public class DataSource
{
@Id
@Column(name = "unique_key")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private long id;
@JoinColumn(name = "source_type_key")
@ManyToOne(targetEntity = DataSourceType.class, fetch = FetchType.LAZY)
private DataSourceType sourceType;
@OneToMany(targetEntity = Message.class, mappedBy = "dataSource", fetch = FetchType.LAZY)
private Set<Message> messages = new HashSet<Message>();
[...]
}
DATA_SOURCE_TYPE:
@Entity
@Table(name="data_source_types", schema="mySchema")
@SequenceGenerator(name="sequence",sequenceName="mySchema.local_key_sequence")
public class DataSourceType
{
@Id
@Column(name="unique_key", unique=true,nullable=false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sequence")
private long id;
@OneToMany(targetEntity=DataSource.class, mappedBy="sourceType",fetch=FetchType.LAZY)
private Set<DataSource> dataSources = new HashSet<DataSource>(0);
[...]
}开发者_C百科
I managed to get this working in HQL, but is there a way to achieve this using Criteria?
try {
crit = session.createCriteria(Message.class, "msg");
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
// UPDATE
// Add your criteria sub query or any ...
}
and add lazy='true'
精彩评论