I have data that looks like this in console:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 700.0
date = 2018-08-01"
Instead I get this for some reason in database:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 70"
My controller:
public class Controller {
private description = "to add: \n"+
"rand_num = 1-231881-6-70885-12 \n"+
"name = heat boy \n"+
"type = caucasian \n"+
"price = 700.0 \n"+
"date = 2018-08-01"
private Model textFields() {
Model model = new Model();
model.setRand_num(description.getText());
}
try {
DAOClass daoClass = new DAOCLass();
daoClass.insert(textFields());
}
catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e) {
System.out.println(e);
}
}
My model:
public class model {
private SimpleStringProperty description;
public Model() {
this("");
}
public model(String description) {
super();
this.rand_num = new SimpleStringProperty(description);
}
//getter
public String getDescription() {
return description.get();
}
//setter
public void setDescription(String description) {
this.description.set(description);
}
//property
public StringProperty descriptionProperty(){
return description;
}
#Override
public String toString() {
return "to add: " +
}
}
DAO class
public class DAO {
public void insert(Model model) throws SQLException, ClassNotFoundException {
//initializing PreparedStatement
PreparedStatement preparedStatement = null;
String updateQuery =
"INSERT INTO modelDB \n" +
"(description) \n" +
"VALUES \n" +
"(?)";
//Execute DELETE operation
try {
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1, model.description());
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.print("Error: " + e);
throw e;
}
finally {
if(preparedStatement != null)
{
preparedStatement.close();
}
}
}
}
My SQLite table structure:
CREATE TABLE userActivityLogs (
logId INTEGER PRIMARY KEY AUTOINCREMENT,
description VARCHAR (10000)
);
Now I know there is no limit for SQLite and even if there was I am using varChar(10000). It all displays perfectly on console but once it is in the database it is truncated. Why is that and how can I fix this issue?
I dont´t see your random number truncated so the varchar(10000) isn´t at play here.
What i see in your code is:
preparedStatement.setString(4, model.getPrice());
preparedStatement.setString(4, model.getDate());
You are using the same index for Price and Date.
Related
I have three DBs, of which hibernate can only create 2/3. Can someone explain why hibernate can not create a third table "goods"
1: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table goods (ID integer not null, brand varchar(255), desc varchar(255), model varchar(255), price float(53) not null, type varchar(255), primary key (ID)) engine=InnoDB" via JDBC Statement
---> at Models.Main.main(Main.java:18) <---
2: Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255), model varchar(255), price float(53) not null, type varchar(25' at line 1
<persistence
xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="OrderDB">
<properties>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/orderdb"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="qwer1234"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
MAIN:
package Models;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import java.util.List;
import java.util.Scanner;
public class Main {
static EntityManagerFactory emf;
static EntityManager em;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
emf = Persistence.createEntityManagerFactory("OrderDB");
while (true) {
System.out.println("1: add user");
System.out.println("2: add goods");
System.out.println("3: create order");
System.out.println("4: view users");
System.out.println("5: view goods");
System.out.println("6: view orders");
System.out.print("-> ");
String s = sc.nextLine();
switch (s) {
case "1":
addUser(sc);
break;
case "2":
addGoods(sc);
break;
case "3":
createOrder(sc);
break;
case "4":
viewUsers();
break;
case "5":
viewGoods();
break;
case "6":
viewOrders();
break;
default:
return;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
emf.close();
}
}
private static void addUser(Scanner sc) {
System.out.println("Enter information about user:");
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter last name: ");
String lastName = sc.nextLine();
System.out.print("Enter age: ");
String strAge = sc.nextLine();
int age = Integer.parseInt(strAge);
System.out.print("Enter email: ");
String email = sc.nextLine();
System.out.print("Enter phone: ");
String phone = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
User user = new User(name, lastName, age, email, phone);
em.persist(user);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void addGoods(Scanner sc) {
System.out.println("Enter information about product:");
System.out.print("Enter type: ");
String type = sc.nextLine();
System.out.print("Enter brand: ");
String brand = sc.nextLine();
System.out.print("Enter model: ");
String model = sc.nextLine();
System.out.print("Enter price: ");
double price = Double.parseDouble(sc.nextLine());
System.out.print("Enter description: ");
String desc = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Good good = new Good(type, brand, model, price, desc);
em.persist(good);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void createOrder(Scanner sc) {
System.out.println("Enter information about order:");
System.out.print("Enter goods id: ");
int goodID = Integer.parseInt(sc.nextLine());
System.out.print("Enter user id: ");
int userID = Integer.parseInt(sc.nextLine());
System.out.print("Enter order name: ");
String orderName = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Order order = new Order(goodID, userID, orderName);
em.persist(order);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void viewUsers() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT u FROM User u", User.class);
List<User> list = (List<User>) query.getResultList();
for (User u : list)
System.out.println(u);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
private static void viewGoods() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT g FROM Good g", Good.class);
List<Good> list = (List<Good>) query.getResultList();
for (Good g : list)
System.out.println(g);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
private static void viewOrders() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT o FROM Order o", Order.class);
List<Order> list = (List<Order>) query.getResultList();
for (Order o : list)
System.out.println(o);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
}
enter code here
GOODS:
package Models;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "goods")
public class Good {
private int ID;
private String type;
private String brand;
private String model;
private double price;
private String desc;
public Good(String type, String brand, String model, double price, String desc) {
this.type = type;
this.brand = brand;
this.model = model;
this.price = price;
this.desc = desc;
}
public Good() {
}
#Id
#GeneratedValue
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#Override
public String toString() {
return "Good ID: " + ID + System.lineSeparator()
+ "Type: " + type + " " + brand + " " + model + System.lineSeparator()
+ "Price: " + price + System.lineSeparator()
+ "Description: " + desc;
}
}
I went through your code. The only fishy part is
private String desc;
"DESC" is reserved keyword in databases.
If you look closely at the syntax(query) issued in your database,
it will show you
CREATE TABLE goods (ID INTEGER NOT NULL,brand VARCHAR (255),DESC VARCHAR(255), model VARCHAR (255), price FLOAT (53) NOT NULL,TYPE VARCHAR(255), PRIMARY KEY (ID)) ENGINE = INNODB
You can see the "DESC" turns blue and shows that it is reserved keyword for "descending".
Try changing it to something else like "descs" or you can define column and change it to something else like`
#Column(name="descs")
private String desc;
It will work.`
I have a tableview that I am trying to populate from a query I created using a sql database. One of the columns holds a date value and when I run the program I am getting an error that says "com.microsoft.sqlserver.jdbc.SQLServerException: The column name AppointmentDate is not valid." Here is some of my code.
HoustonAppointments.java
//Set variable
java.util.Date AppointmentDate;
//Constructor
public HoustonAppointments(Date appointmentDate) {
AppointmentDate = appointmentDate;
}
//Getter and setter
public java.util.Date getAppointmentDate() {
return AppointmentDate;
}
public void setAppointmentDate(java.util.Date appointmentDate) {
AppointmentDate = appointmentDate;
}
Controller class
public class HoustonAppointmentsController implements Initializable {
//Connect control from FXML
#FXML TableColumn<HoustonAppointments, Date> AppointmentDate;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
//Set cell value factory
AppointmentDate.setCellValueFactory(new PropertyValueFactory<>("AppointmentDate"));
//Query function
try{
ResultSet rs = statement.executeQuery("SELECT Customer.FirstName, Customer.LastName,
City.CityName, Appointments.AppointmentDate as 'Appointment Date'\n" +
"FROM Orders INNER JOIN\n" +
"Customer ON Orders.CustomerID = Customer.CustomerID INNER JOIN\n" +
"ShootLocation ON Orders.LocationID = ShootLocation.LocationID INNER JOIN\n" +
"City INNER JOIN\n" +
"CityState ON City.CityID = CityState.CityID ON ShootLocation.CityStateID =
CityState.CityStateID INNER JOIN\n" +
"Appointments ON Customer.CustomerID = Appointments.CustomerID AND
ShootLocation.LocationID = Appointments.LocationID\n" +
"Where CityName = 'Houston'\n" +
"Order by Appointments.AppointmentDate desc");
while(rs.next()){
shootsObservableList.add(new HoustonAppointments(rs.getDate("AppointmentDate")));
}
conn.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
houstonShootsTableView.setItems(shootsObservableList);
}
}
I'm trying to write a small java application that returns the details for an employee. Here's my Employee class.
public class Employees {
private int id;
private Date dateofBirth;
private String firstName;
private String lastName;
private enum gender{
M, F;
}
private gender employeeGender;
private Date dateHired;
public String getEmployeeGender() {
return this.employeeGender.name();
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = gender.valueOf(employeeGender);
}
/*Getters, setters omitted*/
Here's my DAO class
public class EmployeeDao {
final String TABLE_EMPLOYEES = "employees";
final String COLUMN_EMPLOYEES_ID = "emp_no";
final String COLUMN_EMPLOYEES_DOB = "birth_date";
final String COLUMN_EMPLOYEES_FIRST_NAME = "first_name";
final String COLUMN_EMPLOYEES_LAST_NAME = "last_name";
final String COLUMN_EMPLOYEES_GENDER = "gender";
final String COLUMN_EMPLOYEES_HIRE_DATE = "hire_date";
final String QUERY_EMPLOYEES = "SELECT * FROM " + TABLE_EMPLOYEES + " WHERE " + COLUMN_EMPLOYEES_ID + " = ?";
public Employees getEmployeeDetails(int employeeId) {
Employees employee = new Employees();
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees = databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()) {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return employee;
}
}
But when I try to run the app in main method like this, I get an output with null values.
public static void main(String[] args) {
EmployeeDao employeeDao = new EmployeeDao();
Employees employees = employeeDao.getEmployeeDetails(39256);
System.out.println(employees.getId() + " \n" + employees.getFirstName() + " \n" + employees.getLastName() + " \n" + employees.getDateofBirth() + " \n" + employees.getDateHired());
}
This is the output.
This is how the corresponding row looks like in the database
You should not call next twice, since it will move the cursor forward again. Try this:
if (result.next() == false) {
System.out.println("Empty Resultset");
} else {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
Calling ResultSet#next moves the cursor forward a row, so your if condition loses the first row. Since you know your query can return at most one row, you don't need the while loop at all, however:
public Employees getEmployeeDetails(int employeeId) throws SQLException {
Employees employee = null;
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees =
databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next()) {
employee = new Employees();
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
}
return employee;
}
No need to add extra result.next() comparison.
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()){
}
while will execute only if there are any rows.
Check the size of list generated before using to check if it contains value or not.
Just to let you know:
I know how to use Scanner od BufferedReader, just dont know where to use it in this case.
I am working on my first bigger app in Java.
(I had to use SQLite as a DB)
That's some kind of gym app, where I will add my workouts (4 simple variables)
And then it will be saved in DB and sorted to read out.
My question is...
How should I add an Input from the user?
I have setters and getters and no Idea where this input should be added.
In main class? Should I build a new method?
package bazadanych;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DBConnector d = new DBConnector();
d.addWorkout( "bicek", 12, 5,22052019);
List<Workout> workouts = d.allWorkouts();
for (int i=0; i < workouts.size(); i++) {
System.out.println("---------------------------------");
System.out.println("The name of the excersise: " + workouts.get(i).getName());
System.out.println(" Number of reps: " + workouts.get(i).getReps());
System.out.println(" Weight: " + workouts.get(i).getWeight() + "kg");
System.out.println("Date: " + workouts.get(i).getDate());
System.out.println("---------------------------------");
}
}
package bazadanych;
public class Workout extends DBConnector {
private int workoutId;
private String name;
private int reps;
private int weight;
private int date;
public Workout(int workoutId, String name, int weight, int reps, int date)
{
setWorkoutId(workoutId);
setName(name);
setWeight(weight);
setReps(reps);
setDate(date);
}
// Getters
public int getDate()
{
return date;
}
public int getWorkoutId()
{
return workoutId;
}
public String getName()
{
return name;
}
public int getReps()
{
return reps;
}
public int getWeight()
{
return weight;
}
//Setters
public void setDate(int date)
{
this.date = date;
}
public void setName(String name)
{
this.name = name;
}
public void setReps(int reps)
{
this.reps = reps;
}
public void setWorkoutId(int workoutId)
{
this.workoutId = workoutId;
}
public void setWeight(int weight)
{
this.weight = weight;
}
}
package bazadanych;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
public class DBConnector {
// connection with datebase
private Connection conn;
// The object used to execute a static SQL statement and returning the results
private Statement stat;
// Construct
public DBConnector()
{
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
System.err.println("There is no JDBC driver");
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection("jdbc:sqlite:GymApp.db"); // GymApp will be the name of the datebase
stat = conn.createStatement();
}
catch (SQLException e)
{
System.err.println("I can not connect");
}
CreateStructure();
}
public boolean CreateStructure()
{
// Rule to delete the table and create new, when we want to rework number of columnes etc.
// String dropFirst = "DROP TABLE IF EXISTS workouts;";
String sql = "CREATE TABLE IF NOT EXISTS workouts"
+ "("
+ "workoutId INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name varchar(100),"
+ "reps INTEGER, "
+ " weight INTEGER,"
+ " date INTEGER"
+ ")";
try
{
// stat.execute(dropFirst);
stat.execute(sql);
}
catch (SQLException e)
{
System.err.println("There is a problem by Structure creation");
e.printStackTrace();
return false;
}
return true;
}
public boolean addWorkout( String name, int reps, int weight, int date)
{ String sql = " insert into workouts values (Null,?,?,?,?);";
try
(PreparedStatement pStmt = conn.prepareStatement(sql)){
pStmt.setString(1, name);
pStmt.setInt(2,reps);
pStmt.setInt(3,weight);
pStmt.setInt(4, date);
pStmt.execute();
}
catch(SQLException e)
{
System.err.println("Can not add a new contact");
e.printStackTrace();
return false;
}
return true;
}
public List<Workout> allWorkouts()
{
List<Workout> workouts = new LinkedList<Workout>();
try {
ResultSet show = stat.executeQuery("SELECT * FROM workouts ORDER BY date");
int id;
String name;
int reps;
int weight;
int date;
while (show.next())
{
id = show.getInt("workoutId");
name = show.getString("name");
reps = show.getInt("reps");
weight = show.getInt("weight");
date = show.getInt("date");
workouts.add(new Workout(id, name,reps,weight,date));
}
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return workouts;
}
public void closeConnection() {
try{
conn.close();
}
catch (SQLException e) {
System.err.println("There is connection closing error");
e.printStackTrace();
}
}
}
To answer your main question, you should add the input from the user in the main method. You'd use an instance of Scanner to read the values of workout name, reps and weight. Date you could simply pick up the current date, code sample below.
A few other recommendations:
1 - Change the workout date to long, that's a standard in the industry.
2 - The method CreateStructure does not follow Java coding standards, rename it to createStructure.
3 - You are storing the workout ID as NULL, that could cause you trouble later when trying to retrieve the data from the database.
Code sample:
public static void main(String[] args) {
DBConnector d = new DBConnector();
// Retrieve input from the user
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int reps = sc.nextInt();
int weight = sc.nextInt();
// create the workout with the data
d.addWorkout( name, reps, weight, LocalDate.now().toEpochDay());
List<Workout> workouts = d.allWorkouts();
// print workouts
}
i have generated texo model from EMF.
Following is the code
try{
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Country country = new Country();
country.setCode("PK");;
country.setCountry("PAKISTAN");
System.out.println((Integer) session.save(country));
//^ HERE THE ERROR COMES
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
When i try to add country object with or without locations, I get the error
Failed to create sessionFactory object.java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set
The model is generated by Texo have List and simple getter and setter generated.
I have checked this link. but i dont find any answer.
COUNTRY.java
import java.util.ArrayList;
import java.util.List;
public class Country {
private int iD = 0;
private String country = null;
private String code = null;
private List<Location> locations = new ArrayList<Location>();
public int getID() {
return iD;
}
public void setID(int newID) {
iD = newID;
}
public String getCountry() {
return country;
}
public void setCountry(String newCountry) {
country = newCountry;
}
public String getCode() {
return code;
}
public void setCode(String newCode) {
code = newCode;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> newLocations) {
locations = newLocations;
}
#Override
public String toString() {
return "Country " + " [iD: " + getID() + "]" + " [country: "
+ getCountry() + "]" + " [code: " + getCode() + "]";
}
}
As discussed in Texo , I have to generate SET instead of LIST in java entities in order to work with Hibernate.
So i had to configure the TEXO to do this for all entities.
Generate the Annotation Model.
Find the entity ( locations ) and add new annotation. goto its properties and set USE LIST = FALSE
Generate the texo models and all the required entities will be change from List to Set
please try changing Set<Location> sLoc = new HashSet<Location>(locations); to List<Location> sLoc = new ArrayList<Location>(locations);. U have ur locations as array and sLoc as Hashset so it is giving casting exception..
Hope this solves your problem