Fetching selected attribute in entities
There are two possibilities: You can issue a normal fetch request
and extract an array containing the wanted attribute from the result,
using map()
:
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [Model] {
let friendIDs = map(result) { $0.friendID }
println(friendIDs)
} else {
println("fetch failed: \(error!.localizedDescription)")
}
Swift 2:
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
do {
let result = try context.executeFetchRequest(fetchReq) as! [Model]
let friendIDs = result.map { $0.friendID }
print(friendIDs)
} catch let error as NSError {
print("fetch failed: \(error.localizedDescription)")
}
Or you set the resultType
to .DictionaryResultType
and propertiesToFetch
to the wanted attribute.
In this case the fetch request will return an array of dictionaries:
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType
var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [NSDictionary] {
let friendIDs = map(result) { $0["friendID"] as String }
println(friendIDs)
} else {
println("fetch failed: \(error!.localizedDescription)")
}
Swift 2:
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType
do {
let result = try context.executeFetchRequest(fetchReq) as! [NSDictionary]
let friendIDs = result.map { $0["friendID"] as! String }
print(friendIDs)
} catch let error as NSError {
print("fetch failed: \(error.localizedDescription)")
}
The second method has the advantage that only the specified properties
are fetched from the database, not the entire managed objects.
It has the disadvantage that the result does not include pending
unsaved changes in the managed object context (includesPendingChanges:
is implicitly set to false
when using .DictionaryResultType
).
How to fetch only selected attributes of an entity using Spring JPA?
UPDATE:
As has been pointed out to me, I'm lazy and this can very well be done hence I'm updating my answer after having looked around the web for a proper one.
Here's an example of how to get only the id's and only the names:
@Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
@Query("SELECT r.id FROM RuleVo r where r.name = :name")
List<Long> findIdByName(@Param("name") String name);
@Query("SELECT r.name FROM RuleVo r where r.id = :id")
String findNameById(@Param("id") Long id);
}
Hopefully this update proves helpful
Old Answer:
Only retrieving the specific attributes name/id is not possible as this is not how spring was designed or any SQL database for that matter as you always select a row which is an entity.
What you CAN do is query over the variables in the entity, for instance:
@Repository
public interface RuleRepository extends JpaRepository<RuleVO, Long> {
public RuleVo findOneByName(String name);
public RuleVo findOneByNameOrId(String name, Long id);
public List<RuleVo> findAllByName(String name);
// etc, depending on what you want
}
You can modify these however you want w.r.t. your needs. You can call these methods directly via the autowired repository
See http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ Section 5.3 for more options and examples
Select attribute of another attribute of entity
You can simplify a bit your query:
List<Office> calls = entityManager.createQuery(
"select o " +
"from Country c " +
"join c.gov o " +
"left join fetch o.holder " +
"where c.countryKey = :countryKey ", Office.class )
.setParameter( "countryKey", countryKey )
.getResultList();
For additional explanation, see this section of hibernate documentation.
How to get a specific attribute in a core data entity swift
The problem is that you are creating two records, one with the date
and the other with the time
information instead of one with both date
and time
.
If you have only one entity anyway take advantage of the generic behavior and write the method more specific like
func createEntityDate(date: String, time: String) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newEntity = EntityDate(context: context)
newEntity.date = date
newEntity.time = time
do {
try context.save()
print("saved")
} catch {
print("Failed saving", error)
}
}
If you need to modify attributes of an existing record you have to fetch it, modify and save it back.
In any case it's highly recommended to save the whole date as Date
and use computed properties to extract the date
and time
portion.
Dynamics CRM get selected entity's attribute value
Use the SDK.REST.js
library which ships with the CRM SDK to do this. Include this as a script in your form entity and you can reference the functions to make REST calls.
An example call might look like this:
// Assume we are working with the account entity.
// This call is asynchronous.
SDK.REST.retrieveRecord(entityId, "Account", "val_index", null,
// Success.
function (result) {
var value = result.val_index;
// Do something.
},
// Error retrieving the value.
function (error) {
// Notify the user...
});
Is it possible to fetch the data of only one attribute of an Entity in Core Data?
It depends on a few things; how many entities are you fetching, do you ever want anything else, what is your real performance problem?
First of all use Instruments to make sure that your problem is actually where you think it is. Core data uses faulting and batching to make it very memory and performance efficient. An entity's attribute data is not brought into memory until it is accessed.
If you really want to only fetch a single attribute from your entities then you can make a fetch request with the propertiesToFetch
value set to the attributes you care about. If you do this with a managed object resultType
, then AFAIK I know this will use more memory, as it will make all the result objects be a partial fault (with those properties populated) rather than full faults.
If you use the dictionary resultType
, then you'll get back no managed objects at all, just an array of dictionaries with the relevant attribute populated.
How to retrieve the attribute of related object in linq, select projection
In this case I think that your property:
public int AssignedToPersonId { get; set; }
should be:
public Person AssignedToPerson { get; set; }
in your Ticket class. Mapping to the reference is generally better so that you can access properties like this using Linq. This way the line that is giving you trouble can be:
AssignedTo = AssignedToPerson.Name
The reason it isn't working right now is because Entity Framework has no idea how to convert your line:
Uow.Persons.GetById(m.AssignedToPersonId).Name
to a Query expression. By using a reference mentioned above you will instead create a Join between the two tables and get back the desired data in a single query.
The other and probably less attractive option is to store the Id in your View Model and then do a query for the name outside your Linq query. This will work because you have already retrieve items from the database. Untested example below:
public IQueryable Get()
{
var model = Uow.Tickets.GetAll().OrderByDescending(m => m.DateTimeTag)
.Select(m => new TicketViewModel
{
Id = m.Id,
TicketTitle = m.TicketTitle,
TicketBody = m.TicketBody,
DateTimeTag = m.DateTimeTag,
AssignedToPersonId = m.AssignedToPersonId,
Status = m.Status.ToString(),
NoOfReplys = m.Replys.Count()
}).ToList();
model.ForEach(m => m.AssignedTo = Uow.Persons.GetById(m.AssignedToPersonId).Name);
return model;
}
Note however that this second method is making an additional query to the database for each Ticket object returned in the first query.
Select specific attribute in entity Core Data
setPropertiesToFetch:
Specifies which properties should be returned by the fetch.
- (void)setPropertiesToFetch:(NSArray *)values
Parameters
values
An array of
NSPropertyDescription
objects that specify which properties should be returned by the fetch.Discussion
The property descriptions may represent attributes, to-one relationships, or expressions. The name of an attribute or relationship description must match the name of a description on the fetch request’s entity.
Special Considerations
You must set the entity for the fetch request before setting this value, otherwise NSFetchRequest
throws an NSInvalidArgumentException
exception.
This value is only used if resultType is set to NSDictionaryResultType
.
Availability
Available in iOS 3.0 and later.
Related Topics
How to Install iOS 7.0 and iOS 8.0 Simulators in Xcode 6.1
Avoid Animation of Uicollectionview After Reloaditemsatindexpaths
Remove Tab Bar Item Text, Show Only Image
iOS Launch Images - Driving Me Crazy
Avplayer Shows Black Screen When Playing Multiple Videos in Swift3 iOS
When Does Awakefromnib Get Called
How to Make Nsurlsession Post Request in Swift
Go VS. Return Button in iOS Keyboard for HTML Input Forms
Alamofire with a Self-Signed Certificate/Servertrustpolicy
Present Uialertcontroller from Appdelegate
Getting Data from Each Uitableview Cells Swift
Differentiate Between Screen Lock and Home Button Press on iOS7
Custom Back Indicator Image and iOS 11
Order Two Nsmutablearrays Based on One
Uilabel with Two Different Color Text
Pod Install Command with Error