I have list to be deleted.
My code to delete my list is:
for (MyDataModel dataMo: listData) {
testEJB.delete(dataMo.getPkId(), MyDataModel.class);
}
public void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
Since my list size may be more than 500, data deletion by this method is much time consuming.I want alternative so that deletion is quicker.I need help.
Ok i have got solution on my own for this i used native query.Here i do not have to generate the list too.My code is:
public int deleteUsingNativeQuery(String query){
Query qry = em.createNativeQuery(query );
return qry.executeUpdate();
}
Here i pass the native query "delete from 'table name' where 'condition'" in function deleteUsingNativeQuery and deletion was also quick.
Related
I am trying to use JdbcBatchItemWriter for a domain object RemittanceClaimVO . RemittanceClaimVO has a List of another domain object , ClaimVO .
public class RemittanceClaimVO {
private long remitId;
private List<ClaimVO> claims = new ArrayList<ClaimVO>();
//setter and getters
}
So for each remit id, there would be multiple claims and I wish to use single batch statement to insert all rows.
With plain jdbc, I used to write this object by putting values in batches like below ,
ist<ClaimVO> claims = remittanceClaimVO.getClaims();
if(claims != null && !claims.isEmpty()){
for(ClaimVO claim:claims){
int counter = 1 ;
stmt.setLong(counter++, remittanceClaimVO.getRemitId());
stmt.setLong(counter++, claim.getClaimId());
stmt.addBatch();
}
}
stmt.executeBatch();
I am not sure how to achieve same in Spring Batch by using ItemPreparedStatementSetter.
I have tried similar loop as above in setValues method but values not getting set.
#Override
public void setValues(RemittanceClaimVO remittanceClaimVO, PreparedStatement ps) throws SQLException {
List<ClaimVO> claims = remittanceClaimVO.getClaims();
for(ClaimVO claim:claims){
int counter = 1 ;
ps.setLong(counter++, remittanceClaimVO.getRemitId());
ps.setLong(counter++, claim.getClaimId());
}
}
This seems another related question.
Please suggest.
I'm having some trouble working with a particular ef query. I've simplified everything down as much as I can. I'm only querying for two columns. Here is my model.
[Table("TAXROLL", Schema = "CLAND")]
public class TaxRoll
{
[Key]
[Column("TAXROLL_ID")]
public string Id { get; set; }
[Column("APN")]
public string APN { get; set; }
}
When I execute my query in my controller, if I do firstordefault, the results take as long as 15-18 seconds to return. If I do a where query, the results are almost instantaneous (less than 1 second), (see my commented timing statements below. When I say 15-18 seconds and almost instantaneous, that's where my numbers are coming from).
[ResponseType(typeof(TaxRoll))]
public async Task<IHttpActionResult> Get(string id)
{
//var start = DateTime.Now;
//Debug.WriteLine("Starting Query");
var apnRecord = await ctx.TaxRoll.FirstOrDefaultAsync(x => x.APN == id);
//Debug.WriteLine("Returning APN after " + DateTime.Now.Subtract(start).TotalSeconds);
return Ok(apnRecord);
}
When I query for the primary key (Id), results return consistently fast every single time regardless of how I run the query. This is only a problem when I'm querying for APN. Yes, APN is indexed. It's also unique. I could use it as PK, and in fact I tried that. No dice. I know that executing a query that searches based on APN consistently returns fast when I do it directly against the database.
Any help or direction is greatly appreciated -- I am thoroughly confused.
Your APN Column is NULLABLE that makes EF add OR operator, 99% it makes SQL to "seek" the column (which does not use index). make APN column NOT NULL.
Additionally to the user skalinkin answer, you can set DbContextConfiguration.UseDatabaseNullSemantics property to true.
public class YourDbContext : DbContext
{
public YourDbContext()
{
Configuration.UseDatabaseNullSemantics = true;
// ...
}
}
The query that takes 15-18s
var apnRecord = await ctx.TaxRoll.FirstOrDefaultAsync(x => x.APN == id);
Is same as
var apnRecord = await ctx.TaxRoll.Where(x => x.APN == id).FirstOrDefaultAsync();
If you are using just Where(), nothing will be materialized from the database.
Also consider using Stopwatch instead of calculating timestamps.
var sw = new Stopwatch();
sw.Start();
// do something
Debug.WriteLine(sw.Elapsed);
How can I include a related entity, but only select the top 1?
public EntityFramework.Member Get(string userName)
{
var query = from member in context.Members
.Include(member => member.Renewals)
where member.UserName == userName
select member;
return query.SingleOrDefault();
}
According to MSDN:
"Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities."
http://msdn.microsoft.com/en-us/data/jj574232
There is also a uservoice item for this functionality:
http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method
The approach to use an anonymous object works, even though it's not clean as you wish it would be:
public Member GetMember(string username)
{
var result = (from m in db.Members
where m.Username == username
select new
{
Member = m,
FirstRenewal = m.Renewals.FirstOrDefault()
}).AsEnumerable().Select(r => r.Member).FirstOrDefault();
return result;
}
The FirstRenewal property is used just to make EF6 load the first renewal into the Member object. As a result the Member returned from the GetMember() method contains only the first renewal.
This code generates a single Query to the DB, so maybe it's good enough for You.
I don't know how to create functions to retrieve the values.
*Table 1: OrgVasplans*
-Id
-vasplanId
-OrgId
-CreatedDate
Table-2: vasplans
-Id
-name
-amount
-validity
-vasdurationId
Table-3: VasDuration
Id
Duration.
These are my tables..
I have Controller named Candidatesvas and action method VasDetails....
I already stored the values into vasPlans table.
when I click in view "Details" link it will go to details page..
Then the values are retrieve from "Orgvasplans" table automatically without enter any input..
How to create methods for this....
I created some methods but the method contains only Name "field". I want to retrieve multiple values like "Amount", "validity" like that.....
Repository:
public IQueryable<VasPlan> GetVasPlans()
{
return from vasplan in _db.VasPlans
orderby vasplan.Name ascending
select vasplan;
}
public OrgVasPlan GetOrgVasPlan(int id)
{
return _db.OrgVasPlans.SingleOrDefault(v => v.Id == id);
}
public int AddOrgVasPlan(OrgVasPlan orgvasplan)
{
_db.OrgVasPlans.AddObject(orgvasplan);
Save();
return orgvasplan.Id;
}
public void AddVasPlan(VasPlan vasPlan)
{
_db.VasPlans.AddObject(vasPlan);
}
Controller
public ActionResult VasDetails(FormCollection collection)
{
OrgVasPlan orgvasplan = new OrgVasPlan();
orgvasplan.CreatedDate = DateTime.Now;
orgvasplan.OrgId = LoggedInOrganization.Id;
orgvasplan.vasplanId=??????????????
VasPlan vasplan = new VasPlan();
//if (!string.IsNullOrEmpty(collection["Name"])) ;
_repository.AddOrgVasPlan(orgvasplan);
_repository.Save();
return View();
}
Here i don't know how to put code here for get multiple values form vasplans table like(amount,name,validity etc...,)
this is my problem...
Make your view strongly-typed, make sure you create input elements whose names correspond to the model properties (or use HTML helpers, e.g. Html.TextBoxFor(model => model.Amount). That way MVC will automatically fill in the model for you when the action that should take the model as a argument, is invoked.
For example your action should be:
public ActionResult NewVasPlan(VasPlan vplan)
{
//check model state
//save or return error messages
}
Or you can simply add string and int parameters to the Action like this:
public ActionResult NewVasPlan(string name, int amount /*, etc*/)
{
//MVC will also automatically fill name, amount, from request POST or GET params
//(or cookies??)
}
Hope this helps, tell me if you need more info or if I misunderstood your question.
Hi.
I m using a Invoke Operation which return a class "Product"
public Product GetProductById(int Id)
{
Product Record = this.ObjectContext.Product.Include("Order_Detail").Where(d=>d.ProductID=Id).FirstOrDefault()
return Record;
}
But i m not able to get Order_Detail in the the completed event of the class
InvokeOperation<Product> Invk = ObjProduct.GetProductById();
Invk.Completed += (sender, e) =>
{
if (!Invk.HasError)
{
Product ObjProduct = Invk.Value;
Order objorder=ObjProduct.Order_Detail;
}
};
i m getting ObjProduct.Order_Detail as Null i not known why i m not able to include Order_Detail in this Product entity
I have written [Include] in metadata as well
[Include]
public Order Order { get; set; }
But Still i m not able to get Order_Detail In the collection.
Waiting for a positive response.
This is the expected behavior. Invokes are meant to execute an operation on the server or retrieve a simple object. As you can see, the InvokeOperation callback don't contains the usual Entities/AllEntities properties that make room for Included Entities. I suggest you to use a standard load operation with a parameter to get your data.
public IQueryable<Product> GetProductById(int Id)
{
return this.ObjectContext.Product.Include("Order_Detail").Where(d=>d.ProductID=Id);
}
If what you're trying to achieve is "Non Accumulating Execution" (i.e. don't load your domainContext's entityContainer with the result of the query) than have a look at this post from Mathew Charles