I have some entity mapping to a collection in a mongoDB. However, I have a separate database I want the same code to run against (eg. Constants.db_B). How can I make this parameter dynamic so I can run this without changing the constant and recompiling? If I could pass this as a parameter that would be fine too.
#MongoEntity(collection = "sample", database = Constants.db_A)
public class SomeEntity extends PanacheMongoEntity {
}
I tried using ConfigProperty on the Constants class, but it only injects it on a bean instance and not the class itself.
Is this possible?
It's not possible right now. This has been issued in the quarkus project.
https://github.com/quarkusio/quarkus/issues/14789
It's not the same casuistry than yours but there's a solution made from the Author of that issue, may be helpful for you
https://gitlab.com/ch3rub1/quarkus-mongo-mutitenant
We have used cloud SDK(odata-generator-maven-plugin) and generated the VDM out of our EDMX(defined in xml) file. Now, want to refer some of the fields from VDM as a constant in our POJO class instead of re-defining as a constant in our class . I don’t find EDMX field/odataName declared as a variable with public specifier and the constant as well in VDM generated classes.
In the below example,
For example :
VDM snippet - ItemCDSViewForLineItem.java
#ODataField(odataName = "DraftUUID")
private UUID key_2;
public final static ItemCDSViewForLineItemField<UUID> KEY_2 = new ItemCDSViewForLineItemField <UUID>("DraftUUID");
Edmx snippet:
`<Property Name="DraftUUID" Type="Edm.Guid" sap:label="Key"/>`
Is there any way by which I can access or refer “DraftUUID” as a constant field in our own POJO class and reuse it ? Could you please suggest ?
Thanks
Surendra
You need to add Lombok as a dependency to your project to see the public Getters and Setters for these fields. More information can be obtained from the documentation.
To also see them in your IDE you probably need to have a plugin installed as described here.
The method EntityField#getFieldName should give you what you are looking for:
ItemCDSViewForLineItem.KEY_2.getFieldName() // returns "DraftUUID"
In proyect with Jhipste 4.4.1, Spring Boot, Grandle, MongoDb
#Mapper(componentModel = "spring", uses = {})
public interface OportunidadMapper extends EntityMapper <OportunidadDTO, Oportunidad> {
Is OportunidadDTO ad:
private Long clienteId;
In Oportunidad
#Field("clienteId")
private Long clienteId;
I added a field to the DTO and to the entity but the Mapper does not parse it to me. Do I have to do something else, so that I can recognize it? (They have getter and setter in both classes)
You must recompile your project with gradle so that MapStruct annotation processor re-generates OportunidadMapperImpl class.
I have created an MVC app in which I renamed a model class from "Diplomata" to "Diplomas" and now I can't make the migrations to create a table with name "Diplomas", because they still use the old name for some reason. (using .NET Framework 4.6 and EntityFramework 6.1.2)
things I have tried so far:
dropping the db tables completely (from Visual Studio's SQL Server Object Explorer and deleting the files manually)
deleting the migration folder and re-enabling migrations
deleting the model and re-creating it (after deleting migrations and dropping the tables completely)
After enabling migrations again and using command "add-migration Initial" I get a script that generates a table with name "dbo.Diplomata"
this is the model
namespace DDS.Data.Models
{
using System.Collections.Generic;
using DDS.Data.Common.Models;
public class Diploma : BaseModel<int>
{
public string Title { get; set; }
public string Description { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
this is the ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
...
public IDbSet<Diploma> Diplomas { get; set; }
...
}
and this is the part of the migration script that is automatically generated
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Diplomata",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(),
Description = c.String(),
...
}
Also running a search in VS2015 for "Diplomata" in the entire solution doesn't find anything.
Adding a migration that is renaming the table makes the app crash after the update, because it is searching for a table with the old name. (Invalid object name 'dbo.Diplomata')
I have been debugging this all day with no result so any ideas or suggestions for where and what to look for are appreciated.
PS: This is my first question here so if I missed something or something is hard to understand please tell me, thank you
Did you try cleaning the migrations table? When migrations are enabled, a system table called "__MigrationHistory" is generated. You can locate such table from within SQL Server Management Studio. Go to YourDatabase->Tables->System Tables and it's going to be there.
The way migrations work is as follows:
An initial migration is generated with a specified name.
The initial migration is executed.
When the initial migration and subsequent migrations are run, the changes are applied to the database and a snapshot of the structure of the database it's saved in the __MigrationHIstory table as a new row.
When the application initializaes, EF will compare the latest record in the migrations table and compare that snapshot with the latest migration available, if they don't match, an exception will be thrown. This is how EF determines whether or not the Database changed.
When you are making changes to the original model, you are supposed to create subsequent migration files so you can revert or apply database changes. If you already deleted the initial migration file, probably your best option will be to clean the __MigrationHistory table. EF generates unique entries in the table (I believe that the default behavior is the name of the migration file + a timestamp when the migration was generated). You can always rename the initial migration file to match with the name in the __MigrationHistory table and create a new migration to apply the rename of the table in question. This will only work if the name of the files and model match the snapshots in the DB, otherwise an exception will be thrown
Take a look to this article for more information about migrations:
http://tech.trailmax.info/2014/03/inside_of_ef_migrations/
As a side note, you can also modify the default behavior oh how the migration history table is generated. This may be helpful in the event you need to support specific needs, such as renaming it, not generate it as a system table, add additional columns, etc. This will be helpful in certain scenarios. Check the following link (Particularly useful for cloud-based databases):
How do I add an additional column to the __MigrationHistory table?
NOTE: It is important to mention that tables that are not contained in the initial model or subsequent models will be excluded from the model validation. This is specially useful if you want to create tables that shouldn't be monitored by EF. I.E: The membership provider tables.
I hope this helps clarifying the problems you are having.
After few more trials and errors I gave up on fixing the problem. Instead I forced the app to created the model in a table with the name I wanted by adding Table attribute on the model. So now the model looks like this:
[Table("Diplomas")]
public class Diploma : BaseModel<int>
{
public string Title { get; set; }
public string Description { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
I am duplicating an existing Objective-C TV Show app to a new Swift version using Xcode 6.1 and am having some issues with CoreData.
I have created a model of 4 entities, created their NSManagedObject subclass (in Swift), and all files have the proper app targets set (for 'Compile Sources').
I am still getting this error whenever I try to insert a new entity:
CoreData: warning: Unable to load class named 'Shows' for entity
'Shows'. Class not found, using default NSManagedObject instead.
A few comments:
When saving to Core Data, I use the parent-child context way to allow background threading. I do this by setting up the ManagedObjectContext using:
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
and by saving data using:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
var context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
context.parentContext = self.managedObjectContext!
...rest of core data saving code here...
})
This warning is one of the quirks we have to deal with while the details of the Swift implementation are being ironed out. The warning occurs spuriously, i.e. your setup might work even if you do not follow the steps outlined below.
I have been able to get rid of it in most cases by making sure that the class is set correctly in the model editor. Unlike in many other SOF posts (including answers to this question), the suggestion to include the module name (like MyApp.Shows) has not helped me.
Make sure you check these three items:
1.
Version that works up to Xcode 7 beta 3
Notice that I corrected your entity name to the more appropriate singular.
Version that works for Swift 2.0 in Xcode 7.1
(Should work for Xcode 7 beta 4 and above)
You need to delete the text "Current Product Module" in Module!
2.
You should also follow the frequent recommendation to include
#objc(Show)
just above your class.
Note: If you are using Xcode 7 beta 4 or later, this step is optional.
3.
Also make sure to cast the created managed object to the proper class, as the default would be just NSManagedObject.
var newShow = NSEntityDescription.insertNewObjectForEntityForName("Show",
inManagedObjectContext: context) as Show
SWIFT 2 / XCODE 7 Update:
This issue (see my April 3 comment on this answer as well) is resolved in Swift 2 and XCode 7 beta release by Apple.
So you actually now do not need #objc(myEntity) in Swift as answered by Mundi or using
"MyAppName." before your Class name. It will stop working. So remove these, just put Class name in File and select Current Working Module as Module
and cheers!
But for those using #objc(myEntity) in Swift (like me), you can use this other solution instead which works smoothly.
In the xcdatamodel correct class in. It should look like this:
Here you go. Module.Class is the pattern for CoreData in Swift and XCode 6. You will also need the same procedure when using Custom Policy class in Model Policy or other CoreData stuff. A note: In image, The Name and Class should be Car and MyAppName.Car (or whatever the name of your entity). Here, User is a typo.
When using Xcode 7 and purely Swift, I actually had to remove #objc(MyClass) from my auto-generated NSManagedObject subclass (generated from Editor > Create NSManagedObject Subclass...).
In Xcode 7 beta 2 (and I believe 1), in the model configuration a new managed object of type File is set to the Module Current Product Module and the class of the object is shown in configuration as .File.
Deleting the module setting so it is blank, or removing the full stop so the class name in configuration is just File are equivalent actions, as each causes the other change. Saving this configuration will remove the error described.
In Xcode 6.1.1 you do not need to add the #objc attribute since the base entity is a subset of an objc class (NSManagedObject) (see Swift Type Compatibility. In CoreData the full Module.Class name is required. Be aware the Module name is what is set in Build Settings -> Packaging -> Product Module Name. By default this is set to $(PRODUCT_NAME:c99extidentifier) which will be the Target's name.
With xCode 7 and Swift 2.0 version, you don't need to add #objc(NameOfClass), just change the entity settings in "Show the Data Model Inspector" tab like below -
Name - "Your Entity Name"
Class - "Your Entity Name"
Module - "Current Product Module"
Code for Entity class file will be like (in my code Entity is Family) -
import UIKit
import CoreData
class Family: NSManagedObject {
#NSManaged var member : AnyObject
}
This example is working fine in my app with xCode 7.0 + swift 2.0
Do not forget to replace PRODUCT_MODULE_NAME with your product module name.
When a new entity is created, you need to go to the Data Model Inspector (last tab) and replace PRODUCT_MODULE_NAME with your module name, or it will result a class not found error when creating the persistent store coordinator.
You also need to use (at least with Xcode 6.3.2) Module.Class when performing your cast for example:
Assuming your module (i.e. product name) is Food and your class is Fruit
let myEntity = NSEntityDescription.entityForName("Fruit", inManagedObjectContext: managedContext)
let fruit = NSManagedObject(entity: myEntity!, insertIntoManagedObjectContext:managedContext) as! Food.Fruit
Recap:
Include module name when defining entity in Data Model Editor (Name: Fruit, Class: Food.Fruit)
When accessing the entity in code (i.e.SWIFT), cast it with Module.class (e.g. Food.Fruit)
I also encountered a similar problem, follow these steps to resolve:
The parent is NSManagedObject, not NSObject
The module of an
entity is default, not "Current Product Module"
Changing the Entity Class name in the Data Model editor to correspond to the class in question and adding #objc(NameOfClass) to file of each NSManagedObject right above the class declaration solved this problem for me during Unit Testing.
Most of these answers still seem to apply in Xcode 14. However, my Swift NSManagedObject subclass is included in a custom framework. So what worked for me is: In that Entity inspector, in that Module field (see screenshot in answer by khunsan), type in the name of your framework, for example, MyFramework.
What worked for me (Xcode 7.4, Swift) is changing the class name to <my actual class name>.<entity name>
in the Entity inspector, 'Class' box.
My initiator of the Managed object subclass, looks like this:
convenience init(<properties to init>) {
let entityDescr = NSEntityDescription.entityForName("<entity class name>", inManagedObjectContext: <managed context>)
self.init(entity: entityDescr!, insertIntoManagedObjectContext: <managed context>)}
//init properties here
For Xcode 11.5: if Codegen property is class Definition, and if you are not getting a suggestion for the entity you created in xcdatamodel. Try to quit Xcode and reopen your project again. It works for me. This answer is only if you are not getting suggestions but if your file doesn't get generated try any above answer.