Implement all CRUD operations in StudentSqliteDao

This commit is contained in:
Thibaud Gasser 2019-01-02 23:58:59 +01:00
parent 0d9692992b
commit 4cde30a6e0
4 changed files with 157 additions and 9 deletions

View File

@ -1,20 +1,27 @@
package fr.gasser.daoexample.dao; package fr.gasser.daoexample.dao;
import fr.gasser.daoexample.model.Discipline;
import fr.gasser.daoexample.model.Student;
import fr.gasser.daoexample.model.Teacher;
import fr.gasser.daoexample.sql.Connection;
import fr.gasser.daoexample.sql.SQLiteConnection;
public class SqliteDaoFactory implements DaoAbstractFactory { public class SqliteDaoFactory implements DaoAbstractFactory {
private static Connection conn = new SQLiteConnection();
@Override @Override
public StudentDao createStudentDao() { public Dao<Student> createStudentDao() {
return new StudentSQLiteDao(conn);
}
@Override
public Dao<Teacher> createTeacherDao() {
return null; return null;
} }
@Override @Override
public TeacherDao createTeacherDao() { public Dao<Discipline> createDisciplineDao() {
return null;
}
@Override
public DisciplineDao createDisciplineDao() {
return null; return null;
} }
} }

View File

@ -0,0 +1,132 @@
package fr.gasser.daoexample.dao;
import fr.gasser.daoexample.model.Student;
import fr.gasser.daoexample.sql.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentSQLiteDao extends Dao<Student> {
private static final Logger LOGGER = LoggerFactory.getLogger(StudentSQLiteDao.class);
public StudentSQLiteDao(Connection connection) {
super(connection);
try {
connection.connect();
dropAndCreateTable(connection);
} catch (SQLException e) {
LOGGER.error("Unable to connect to the database.", e);
}
}
private void dropAndCreateTable(Connection connection) throws SQLException {
try (Statement st = connection.getConnection().createStatement()) {
st.setQueryTimeout(30); // set timeout to 30 sec.
st.executeUpdate("DROP TABLE IF EXISTS students");
// In SQLite, table rows normally have a 64-bit signed integer ROWID
// which is unique among all rows in the same table.
// When a new row is inserted into an SQLite table, the ROWID can either be specified as part of the INSERT
// statement or it can be assigned automatically by the database engine.
st.executeUpdate("CREATE TABLE students (name TEXT NOT NULL, surname TEXT NOT NULL)");
}
}
@Override
public boolean create(Student obj) {
final String sql = "INSERT INTO students (name, surname) VALUES (?, ?)";
try (PreparedStatement st = connection.getConnection().prepareStatement(sql)) {
st.setObject(1, obj.getName());
st.setObject(2, obj.getSurname());
final int ret = st.executeUpdate();
LOGGER.info("" + ret);
return ret != 0;
} catch (SQLException e) {
LOGGER.error("", e);
}
return false;
}
@Override
public Student find(int id) {
try (PreparedStatement st = connection.getConnection().prepareStatement("SELECT rowid,* FROM students WHERE rowid = ?")) {
st.setObject(1, id);
final ResultSet rs = st.executeQuery();
final String name = rs.getString("name");
final String surname = rs.getString("surname");
return new Student(id, name, surname);
} catch (SQLException e) {
LOGGER.error("", e);
}
return null;
}
@Override
public List<Student> findAll() {
List<Student> results = new ArrayList<>();
try (Statement st = connection.getConnection().createStatement()) {
ResultSet rs = st.executeQuery("select rowid,* from students");
while (rs.next()) {
final int id = rs.getInt("rowid");
final String name = rs.getString("name");
final String surname = rs.getString("surname");
results.add(new Student(id, name, surname));
}
} catch (SQLException e) {
LOGGER.error("", e);
}
return results;
}
@Override
public boolean update(Student obj) {
try (PreparedStatement st = connection.getConnection().prepareStatement("UPDATE students SET name = ?, surname = ? WHERE rowid = ?")) {
st.setString(1, obj.getName());
st.setString(2, obj.getSurname());
st.setInt(3, obj.getId());
st.executeUpdate();
return true;
} catch (SQLException e) {
LOGGER.error("", e);
}
return false;
}
@Override
public boolean delete(Student obj) {
String deleteSQL = "DELETE FROM students WHERE rowid = ?";
try (PreparedStatement st = connection.getConnection().prepareStatement(deleteSQL)) {
st.setInt(1, obj.getId());
st.executeUpdate();
return true;
} catch (SQLException e) {
LOGGER.error("", e);
}
return false;
}
/**
* Quick testing of CRUD operations
* @param args
*/
public static void main(String[] args) {
DaoAbstractFactory df = DaoAbstractFactory.createFactory(FactoryType.SqliteDaoFactory);
final Dao<Student> dao = df.createStudentDao();
dao.create(new Student(1, "Thibaud", "Gasser"));
dao.create(new Student(2, "Azerty", "Uiop"));
final Student s = dao.find(1);
System.out.println(s);
s.setName("Foo");
dao.update(s);
System.out.println(dao.findAll());
dao.delete(s);
System.out.println(dao.findAll());
}
}

View File

@ -21,13 +21,13 @@ public class SQLiteConnection implements Connection {
} }
@Override @Override
public void connect() { public void connect() throws SQLiteConnectionException {
try { try {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dbpath); connection = DriverManager.getConnection("jdbc:sqlite:" + dbpath);
LOGGER.info("Connected to {} successfully.", dbpath); LOGGER.info("Connected to {} successfully.", dbpath);
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {
LOGGER.error("Unable to connect to the database.", e); throw new SQLiteConnectionException(e.getMessage());
} }
} }

View File

@ -0,0 +1,9 @@
package fr.gasser.daoexample.sql;
import java.sql.SQLException;
public class SQLiteConnectionException extends SQLException {
public SQLiteConnectionException(String message) {
super(message);
}
}