Table not found exception using javalite - sql

So I have a very simple table I made in SQL using h2
CREATE TABLE USERS(
username varchar(255) NOT NULL,
password varchar(255),
);
I'm trying to use javalite to add an entry to it so I made this following the instructions on the site.
package DBTEST;
import org.javalite.activejdbc.Base;
public class makeDB {
public static void main(String[] args) {
Base.open("org.h2.Driver", "jdbc:h2:./test", "sa", "");
User e = new User();
e.set("username", "John");
e.set("password", "Doe");
e.saveIt();
User.findAll().dump();
Base.close();
}
}
I have a class Users for this table
package DBTEST;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
#Table("USERS")
public class User extends Model {
}
I keep getting this exception
Exception in thread "main" org.javalite.activejdbc.DBException: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "USERS" not found; SQL statement:
Can anyone help? I have no idea why this is happening

First, your SQL has an extra comma in "CREATE USERS" statement. The errors says: "able "USERS" not found" - this mean you simply do not have a table!
Second, the table definition is missing an id, please see https://javalite.io/surrogate_primary_keys
Third, I created a simple example project and added your code there. It is working as expected. The project can be found here: https://github.com/javalite/h2-example
The output from running this program looks like this:
Model: activejdbc.examples.simple.User, table: 'users', attributes: {ID=1, PASSWORD=Doe, USERNAME=John}
which is exactly as expected.
Additionally, the #Table annotation is not necessary: https://javalite.io/english_inflections

Related

Why adding a column and index in single migration script results in "Column name ... does not exist" warning?

Assuming there exists table [dbo].[Foo], I created following migration definition:
public partial class Foobar : DbMigration
{
public override void Up()
{
AddColumn("dbo.Foo", "Bar", c => c.DateTime());
CreateIndex("dbo.Foo", "Bar");
}
public override void Down()
{
[...]
}
}
And that generates following SQL (I used Update-Database -script in Nuget Package Console to check that):
ALTER TABLE [dbo].[Foo] ADD [Bar] [datetime]
CREATE INDEX [IX_Bar] ON [dbo].[Foo]([Bar])
When I try to launch SQL above manually I get the warning "Column name Bar does not exist in the target table or view.". But when I launched migration using Update-Database then the migration has been applied succesfully.
What is the difference between manually launching SQL generated by Update-Database -script and SQL execution using Update-Database?

Extending Shopware entity with foreign keys fails when merging version

I'm developing my first Shopware 6 admin plugin, for which is required to extend one of the existing Shopware plugins - Custom products.
I want to add a relation between already existing entities - TemplateExclusion and TemplateOptionDefinition. When I select from the UI my options, TemplateExclusion entity its getting saved in the database, without any problems.
When I save the Template entity (parent of TemplateExclusion), my "excluded_option_id" its getting overwritten with the 1st possible option from TemplateOptionDefinition entities.
I have notice that this is happening on "mergeVersion". Also when I try to save the Template entity with debug mode enabled and profiler, I'm getting an error during saving, that "excludedOptionId" is blank when merging, which is not true.
Error in profiler
Following the documentation I made first the migration:
class Migration1643023742TemplateExclusionRelation extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1643023742;
}
public function update(Connection $connection): void
{
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD COLUMN `excluded_option_id` BINARY(16) AFTER `template_version_id`;');
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD COLUMN `excluded_option_version_id` BINARY(16) AFTER `excluded_option_id`;');
$connection->executeStatement('ALTER TABLE `swag_customized_products_template_exclusion` ADD CONSTRAINT `fk.swag_cupr_template_exclusion.excluded_option_id` FOREIGN KEY (`excluded_option_id`, `excluded_option_version_id`)
REFERENCES `swag_customized_products_template_option` (`id`, `version_id`) ON DELETE CASCADE ON UPDATE CASCADE;');
}
then I made an entity extension, where to define the new fields.
class TemplateExclusionExtension extends EntityExtension
{
public function extendFields(FieldCollection $collection): void
{
$collection->add(
(new FkField('excluded_option_id', 'excludedOptionId', TemplateOptionDefinition::class))
->addFlags(new Required(), new ApiAware())
);
$collection->add(
(new ManyToOneAssociationField('excludedOption', 'excluded_option_id', TemplateOptionDefinition::class))
->addFlags(new ApiAware())
);
$collection->add(
(new ReferenceVersionField(TemplateOptionDefinition::class, 'excluded_option_version_id'))
->addFlags(new Required(), new ApiAware()),
);
}
public function getDefinitionClass(): string
{
return TemplateExclusionDefinition::class;
}
}
Solved:
It was wrong definition from my side:
public function extendFields(FieldCollection $collection): void
{
$collection->add(
(new FkField('excluded_option_id', 'excludedOptionId', TemplateOptionDefinition::class))
->addFlags(new Required(), new ApiAware())
);
$collection->add(
(new OneToOneAssociationField(
EasyExtendCustomizedProducts::TEMPLATE_EXCLUSION_EXCLUDED_OPTION_EXTENSION,
'excluded_option_id',
'id',
TemplateOptionDefinition::class,
false
))->addFlags(new CascadeDelete(), new ApiAware())
);
}
public function getDefinitionClass(): string
{
return TemplateExclusionDefinition::class;
}
If I'm not mistaken the issue was the missing CascadeDelete delete flag.
To versionize the entity it is first fetched including its associated data and is then persisted with new primary keys, so basically it gets cloned. However not all associations are taken into account when fetching the data to be cloned. You can find the responsible code here, where the affected associations get filtered by the existence of the CascadeDelete flag. If they miss the flag they will be ignored for creating the cloned version. This behavior still needs to be documented more prominently.

Sqflite table not created

I'm building a simple app which requires two tables in a database. To create the tables and the database I use the following syntax->
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sqlite_api.dart';
class DBHelper {
static Future<Database> database() async {
final dbPath = await sql.getDatabasesPath();
return sql.openDatabase(path.join(dbPath, 'users.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE user_profile(id TEXT PRIMARY KEY, name TEXT, address TEXT,mobileno TEXT,dob TEXT);CREATE TABLE user_transactions(id TEXT PRIMARY KEY, date TEXT, amount TEXT,cart TEXT)');
}, version: 1);
}
When I excuete a method to add data to the the table 'user_transactions' it gives me an error as 'E/SQLiteLog(24687): (1) no such table: user_transactions
'. The fetching and adding data to user_profile works perfectly fine. I also executed the sql query in db browser for sqlite and no error was found there.I also tried uninstalling the app and installing it again.Please help
I think the best solution to create multiple tables in SQLite is this instead of yours:
class DBHelper {
Future<Database> database() async {
return openDatabase(
join(await getDatabasesPath(), 'users.db'),
onCreate: (db, version) async {
await db.execute(
"CREATE TABLE user_profile(id TEXT PRIMARY KEY, name TEXT, address TEXT,mobileno TEXT,dob TEXT)");
await db.execute(
"CREATE TABLE user_transactions(id TEXT PRIMARY KEY, date TEXT, amount TEXT,cart TEXT)");
return db;
},
version: 1,
);}
Just Uninstall the app and re-install the app. Why it works ?
You might already have users.db db created for the app and onCreate is executed when db is created for the first time, so uninstalling and re-installing the app would solve the problem.

In JSF,how to get parameter values form my sql to jsf the page?

I first made a sql, zdsql, for this project:
create table zdsql(
id integer primary key,
filter varchar(12),
value varchar(12),
descri varchar(12),
standard_number integer,
language varchar(12)
);
insert into zdsql values(1,'zdlj','1','1.rid',1,'en');
insert into zdsql values(2,'zdlj','2','2.ria',1,'en');
Next, I made the JSF, the following codes is the maining of my xhtml:
<h:outputLabel value="#{msgs.zdlj}" style="font-weight:bold" />
<p:selectOneMenu id="zdlj1" value="#{zsjBean.zdlj}">
<f:selectItems value="#{zdsqlBean.zdsqls}" var="bll1"
itemLabel="#{bll1.descri}" itemValue="#{bll1.value}" />
</p:selectOneMenu>
The follwing codes is the maining of zdsqlBean:
package bean;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.TypedQuery;
import model.Zdsql;
import util.DBDAO;
public class ZdsqlBean {
private List<Zdsql> zdsqls;
public ZdsqlBean() {
this.genzdljs();
}
public List<Zdsql> getZdsqls() {
System.out.println("zdsqls==");
return zdsqls;
}
public void setZdsqls(List<Zdsql> zdsqls) {
this.zdsqls = zdsqls;
}
public void genzdljs() {
try {
String queryString = "select m from Zdsql m where m.filter = :filter Order by m.id";
TypedQuery<Zdsql> query = DBDAO.getEntityManager().createQuery(
queryString, Zdsql.class);
query.setParameter("filter", "zdlj");
zdsqls = query.getResultList();
} catch (Exception re) {
DBDAO.log("genzdljs() failed", Level.SEVERE, re);
}
}
However, I still don't get the right values. When I run this project, the selectonemenu has nothing, which should have two selectitems, the values should be same as sql.
From comments, the problem is that you haven't configured the ZdsqlBean as managed bean. There are two ways to do this:
Add the configuration in faces-config.xml file:
<managed-bean>
<managed-bean-name>zdsqlBean</managed-bean-name>
<managed-bean-class>bean.ZdsqlBean</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
</managed-bean>
Since JSF 2, use the #ManagedBean annotation to decorate the class.
#ManagedBean(name="zdsqlBean") //name is optional
public class ZdsqlBean {
//class definition
}
This is covered in a decent JSF tutorial, you can find some in StackOverflow JSF wiki. If you're learning/reading JSF 1.x resources, drop them and go with JSF 2. Note that currently it's in version 2.2.
Thanks Polppan a lot! I add ManagedBean in faces-config.xml, then I get the right result! Thanks for everyone's help!
But I firstly used this website, could you tell me how to close the question and choose the best answer?

Cannot instantiate a Zend_Table in Zend Framework

I'm using Zend Framework version 1.7.8.
I am trying to create a class that extends from Zend_Db_Table_Abstract:
class My_Model_Table extends Zend_Db_Table_Abstract {
public function __construct($tableName) {
parent::__construct(array('name' => $tableName, 'primary' => 'dummy', 'db' => Zend_Registry::get('dbAdapter')));
}
}
However, when I try to fetch from this table:
$table = new My_Model_Table('dual');
Zend_Debug::dump($table->fetchAll());
I am getting this exception:
Primary key column(s) (dummy) are not columns in this table (DUMMY)
For those of you not familiar with Oracle, the DUAL table is a standard Oracle table which has only one column: DUMMY. From what I can see in the error message, ZF is trying to fetch from the "DUMMY" table which doesn't exist. Am I right? What am I doing wrong?
Thanks!
Have you tried:
Class VCCE_Model_Table extends Zend_Db_Table_Abstract {
protected $_name = 'DUAL';
}
$table = new VCCE_Model_Table();
Zend_Debug::dump($table->fetchAll());
Note: in your example you use two different names for your table VCCE_Model_Table and My_Model_Table.
Did you check the configuration settings for dbAdapter?