While compiling:
CREATE TABLE IF NOT EXISTS `SeasonMasterDB`
(`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`id` TEXT PRIMARY KEY AUTOINCREMENT, `name` TEXT
);
that is why you are getting an error. Please help me, this is my code:
#Table(name = "SeasonMasterDB",database = AppDatabase.class)`enter code here`
public class SeasonMasterDB extends Model {
#PrimaryKey
public Long id;
#Column(name = "id")
public String idValue;
#Column(name = "name")
public String name;
public SeasonMasterDB()
{
}
public SeasonMasterDB(String name,String id)
{
this.idValue = id;
this.name = name;
}
}
You cannot have two columns with the same name. Rename one of your id columns.
Related
I began 2 days ago to use Spring MVC and I meet some issues with a case study.
I created a basic table categories (category_id refers to a category id):
DROP TABLE IF EXISTS `categories`;
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL,
`category_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_CATEGORY_CATEGORY` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `categories`
ADD CONSTRAINT `FK_CATEGORY_CATEGORY` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`);
Now my issue is to display the full list of categories with their children if they exist ...
I have in my controller this method which returns a list in JSON :
#GetMapping(path="/categories", produces= {"application/json"})
public List<Category> getAllCategories(Model model) {
return categoryRepository.findAll();
}
It is recommended to do this :
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#ManyToOne
private Category parentCategory;
#OneToMany(mappedBy="parentCategory", fetch = FetchType.EAGER)
private List<Category> childCategories;
... default constructor, getters & setter etc.
}
While trying to view the page i can see the categories but i don't display if they have subcategories or not .... For example this category shoud give a list of children categories ... For example i shoud have in child categories id = 5, name = ..., etc., id =6, id = 7...
{
"id": 1,
"name": "XXX",
"createdat": 1541872732000,
"updatedat": 1541872732000,
"parentCategory": null,
"childCategories": [
]
....
}
and this category who have a parent category returns no parent whereas the parentCategory value should be 1 :
{
"id": 14,
"name": "xxxxxx",
"createdat": 1541873447000,
"updatedat": 1541873447000,
"parentCategory": null,
"childCategories": [
]
....
}
Thanks for your help.
Here is the solution i found :
#Entity
#Table(name="categories")
#NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="name")
private String name;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="category_id")
#JsonBackReference
private Category parentCategory;
#OneToMany(mappedBy="parentCategory", fetch = FetchType.EAGER)
#JsonManagedReference
private List<Category> childCategory;
public Category() {
}
public Category(String name) {
this.name = name;
}
// getters & setters
}
I am using entity manager to persist data into the database. Data is inserting successfully, but when try to fetch the data it doesn't fetch the child data.
Incident.java
#Entity
#Table(name = "Incident")
public class Incident {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "incidentID")
private Integer incidentID;
#Column(name = "incidentTitle")
private String incidentTitle;
#Column(name = "date")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date incidentDate;
#Column(name = "incidentContent")
private String incidentContent;
#ManyToOne
#JoinColumn(name = "countryID")
private Country country;
// Getter and setters
}
Country.java
#Entity
#Table(name="Country")
public class Country {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#NotNull
#Column(name = "name")
#Size(min = 8, max = 100)
private String name;
// getter and setters
}
DAO.java
public Incident addIncident(Incident incident) {
em.getTransaction().begin();
em.persist(incident);
em.flush();
em.getTransaction().commit();
return incident;
}
When i add data into incident table, countryId added successfully but when i try to fetch the same record, countryId comes but name doesn't come.
But when i try to update same record or bounce server or redeploy the application then all data comes successfully along with name.
Couldn't understand the issue.
Can you please help me.
Here's complete code to create a SQLite database, fill some data into a table and then try to retrieve it. If there's an aggregate function around a datetime column, PetaPoco will throw an error.
using System;
using PetaPoco;
class Program
{
static void Main(string[] args)
{
bool filenew = false;
if (!System.IO.File.Exists(#"c:\temp\database.sq3"))
filenew = true;
System.Data.SQLite.SQLiteConnection sqltc = new System.Data.SQLite.SQLiteConnection("Data Source=" + #"c:\temp\database.sq3");
sqltc.Open();
PetaPoco.Database db = new Database(sqltc);
if (filenew)
db.Execute("create table test1 (ID_CHANNEL integer primary key autoincrement, dtfld DateTime null, name string)");
test1 t = new test1();
t.name = "No Date";
db.Insert(t);
t = new test1();
t.dtfld = DateTime.Now;
t.name = "with date";
db.Insert(t);
// SUCCESS:
test1 lt1 = db.First<test1>("select dtfld from test1 where ID_Channel = 2");
// FAILURE:
test1 lt2 = db.First<test1>("select max(dtfld) as dtfld from test1 where dtfld is not null");
}
[PetaPoco.TableName("test1")]
[PetaPoco.PrimaryKey("ID_Channel")]
public class test1
{
public long ID_Channel { get; set; }
public DateTime? dtfld { get; set; }
public string name { get; set; }
}
}
Can anybody suggest a fix that still means the POCO object contains a datetime, and I can still access the max of a date?
Found a solution - switch to NPoco. The only change to above was to replace "PetaPoco" with "NPoco".
In PetaPoco.cs change the private static Func<object, object> GetConverter function. Replace the statement return Convert.ChangeType(src, dstType, null);
TypeConverter conv = TypeDescriptor.GetConverter(dstType);
return conv.ConvertFrom(src);
I am trying to store some custom object as a blob in SqlLite db. The object is a field of a class extending Model. All other fields (of primitive types) go successfully in the DB, but the custom one - it is null always.
#Table(name = "data")
public class Data extends Model {
#Column(name = "number")
private int number;
#Column(name = "blob")
private Contact blob;
...
This is how i store the entity
Data data = new Data(0, new Contact(id, name, number));
data.save();
Here is the contact class
public class Contact {
private String id;
private String name;
private String number;
...
I believe a TypeSerializer is needed, so I've created one.
public class ContactSerializer extends TypeSerializer {
private static final String ELEMENTS_DELIMITER = ";";
#Override
public Object deserialize(Object asString) {
String[] afterSplit = ((String) asString).split(ELEMENTS_DELIMITER);
return new Contact(afterSplit[0], afterSplit[1], afterSplit[2]);
}
#Override
public Class<?> getDeserializedType() {
return Contact.class;
}
#Override
public SerializedType getSerializedType() {
return SerializedType.STRING;
}
#Override
public Object serialize(Object asContact) {
Contact temp = (Contact) asContact;
return temp.getId() + ELEMENTS_DELIMITER + temp.getName() + ELEMENTS_DELIMITER
+ temp.getNumber();
}
}
When i query the db I got object with this particular field "Contact" as null always. Where might be the problem? Do I need to specify which is the TypeSerializer for my object? Or the implementation of TypeSerializer I've created is wrong?
You also need to extent Contact from Model:
#Table(name = "contact")
public class Contact extends Model{
#Column(name = "id")
private String id;
#Column(name = "name")
private String name;
#Column(name = "number")
private String number;
}
Now everything should work out of the box. It's a bit late for a response but perhaps I will help someone else.
I am attempting to save user preferences into a table but am getting a null exception and I do not understand why. This is an MVC 4 application and this is my action result where I am getting the error.
public ActionResult Go(string path, string name)
{
RaterContext r = new RaterContext();
UserData u = new UserData();
var userid = u.GetCurrentUserData().UserId;
var info = r.RatersInfo.Where(w => w.RaterName.Equals(name)).FirstOrDefault();
var pref = r.RatersPreferences.Where(w => w.RaterId.Equals(info.RaterId) && w.UserId.Equals(userid)).FirstOrDefault();
if (pref != null && pref.Count > 0)
{
pref.Count++;
r.SaveChanges();
}
else
{
pref = new RaterPreferences();
pref.UserId = userid;
pref.RaterId = info.RaterId;
pref.Count = 1;
r.RatersPreferences.Add(pref);
r.SaveChanges();
}
return Redirect(path);
}
There is nothing saved in the preferences table yet so it is hitting the else block and throwing a null exception on r.SaveChanges();. The exception is
Cannot insert the value NULL into column 'UserId', table
'WebSiteNew.dbo.RaterPreferences'; column does not allow nulls. INSERT
fails.\r\nThe statement has been terminated.
The reason this doesn't make sense is because all three properties, including the UserId have data when I step through. These are the only fields in the table. UserId = 1, RaterId = 6 and Count is clearly set to 1. They are all set as non-nullable ints and the primary key is a combination of UserId and RaterId. My Model is as follows.
public class RaterContext : DbContext
{
public RaterContext()
: base("DefaultConnection")
{
}
public DbSet<RaterInfo> RatersInfo { get; set; }
public DbSet<RaterPreferences> RatersPreferences { get; set; }
}
[Table("RaterInfo")]
public class RaterInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RaterId { get; set; }
public string RaterName { get; set; }
public string RaterLink { get; set; }
public string Section { get; set; }
public string Department { get; set; }
}
[Table("RaterPreferences")]
public class RaterPreferences
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public int RaterId { get; set; }
public int Count { get; set; }
}
Any help would be greatly appreciated as I am relatively new to MVC and ASP.NET. Let me know if you need more information. Thanks in advance!
I don't know if this helps but I tested to see what would happen on UPDATE by adding data manually so it would catch on the if block and that works. I'm only getting an error on INSERT.
Here is the create statement for the table in question.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RaterPreferences](
[UserId] [int] NOT NULL,
[RaterId] [int] NOT NULL,
[Count] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RaterId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[RaterPreferences] WITH CHECK ADD CONSTRAINT [FK_RaterPreferences_RaterInfo] FOREIGN KEY([RaterId])
REFERENCES [dbo].[RaterInfo] ([RaterId])
GO
ALTER TABLE [dbo].[RaterPreferences] CHECK CONSTRAINT [FK_RaterPreferences_RaterInfo]
GO
I have copied your code into a brand new ASP.Net MVC project with the current version of Entity Framework and I am able to run your code with no problems. I escaped the UserData acquisition with code that looks like:
RaterContext r = new RaterContext();
//UserData u = new UserData();
var userid = 1; // u.GetCurrentUserData().UserId;
var info = r.RatersInfo.Where(w => w.RaterName.Equals(name)).FirstOrDefault();
and did not have a problem running the remainder of this code.
I think you may have some problems with your keys and database structure for the RaterPreferences table. I don't know your full data-model, but I don't understand how this fits in, and it is not keyed in your code the way that you describe.
Edit:
I've modified my database tables to reflect the design you've described. You have a difference between your EntityFramework code-first implementation and your database. It looks like your database existed first, and I would remove your EntityFramework classes and rebuild them with Database First techniques.