Удаление данных в таблице
Что просто делать в SQL, так это удалять данные. Ты можешь удалить абсолютно все очень быстро, и у тебя даже никто не спросит никаких подтверждений.
Начнем с самого простого сценария: как удалить одну строку в таблице.
Этот сценарий ты будешь встречать чаще всего, обычно это удаление какой-то конкретной записи, и стандартный запрос обычно имеет вид:
DELETE FROM таблица WHERE id = 133;
Это единственный запрос, где не нужно указывать имена колонок: данные ведь удаляются сразу строками.
Второй сценарий – это удаление строк, которые заданы списком id, тут тоже все довольно просто:
DELETE FROM таблица WHERE id IN (1, 2, 3, …);
Третий сценарий – это удаление строк, которые соответствуют определенному условию:
DELETE FROM таблица WHERE условие;
Допустим, мы хотим уволить всех наших программистов, тогда нужно написать запрос типа:
DELETE FROM employee WHERE occupation = 'Программист';
И, наконец, если ты хочешь удалить все записи, то можешь написать такой запрос:
Такого простого запроса достаточно, чтобы удалить все записи из таблицы. Кстати, никакого Ctrl+Z при этом не будет. Записи просто удаляются без возможности восстановления и все. Так что делай бэкапы, да почаще.
5.2 Удаляем вообще все
Для быстрого удаления (чтобы добавить юзерам головной боли) у SQL есть еще несколько команд.
Как быстро удалить все данные в таблице? Воспользуйся оператором TRUNCATE :
Одна опечатка в названии таблицы — и пара дней восстановления данных тебе обеспечены. Радуйся, что ты не админ баз данных.
Если тебе нужно удалить не просто данные в таблице, а и саму таблицу, то для этого есть оператор DROP :
Кстати, аналогичные варианты есть и со схемами баз данных. Если хочешь удалить саму базу, то:
DROP DATABASE база_данных
Также с помощью DROP можно удалять:
И вот тебе пару интересных историй, связанных с удалением данных:
Java hibernate удаление таблицы
You need to manually create and delete a table in the database using SQL queries using Hibernate. Class-essence, based on the table:
Hibernate configuration setting occurs in the following utility class:
Public Class Util < Private Static Final String DRIVER= "com.mysql.cj.jdbc.driver"; Private Static Final String URL= "JDBC: MySQL: //Localhost: 3306 /Usersdb? AutoreConnect= True & Usessl= false "; Private Static Final String Username= "Root"; Private Static Final String Password= "Root"; Private Static SessionFactory SessionFactory; Public SessionFactory GetSessionFactory () < if (sessionfactory== null) < try < Configuration Configuration= New Configuration (); Properties Settings= New Properties (); settings.put (environment.driver, driver); settings.put (environment.url, url); settings.put (Environment.user, UserName); settings.put (Environment.pass, Password); settings.put (environment.dialact, "org.hibernate.dialate.mysqldialact"); settings.put (environment.show_sql, "true"); settings.put (environment.current_session_context_class, "thread"); settings.put (environment.hbm2ddl_auto, "Create-Drop"); Configuration.SetProperties (Settings); Configuration.AddannotatedClass (user.class); ServicEREGISTRY SERVICEREGISTRY= New StandardserviceregistryBuilder () .Applysettings (configuration.getProperties ()). Build (); SessionFactory= Configuration.BuildSessionFactory (ServicEREGISTRY); >Catch (Exception E) < System.out.printLN ("Problem Creating Session Factory"); E.PrintStackTrace (); >> RETURN SESSIONFACTORY; >
Methods for creating and deleting a table:
Public Void CreateUserStable () < Session Session= GetSessionFactory (). OpenSession (); Transaction transaction= session.beginransaction (); SQL= "CREATE TABLE IF NOT EXISTS Users" + "(ID BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY," + "Name Varchar (50) Not Null, Lastname Varchar (50) Not NULL," + "AGE TINYINT NOT NULL)"; Query query= session.createSqlQuery (SQL) .addentity (user.class); transaction.commit (); session.close (); >Public void DropusersTable ()
I can’t make these methods work. The table is created, but I suspect that this happens automatically thanks to the Hibernate configuration. It is possible, the case in the HBM2DL_AUTO parameter; I tried to change its value to Update, but it does not help, just the table is no longer created automatically.
How to make methods work, what did I do wrong?
It turned out, forgot to update the query: query.executeUpdate (). Under some changes in the table, the query should be updated, and, let’s say, when receiving data from the table without its change, the request is not necessary. Only now it understood.
It turned out, forgot to update the query: query.executeUpdate (). Under some changes in the table, the query should be updated, and, let’s say, when receiving data from the table without its change, the request is not necessary. Only now it understood.
Java hibernate удаление таблицы
All times are UTC — 5 hours [ DST ]
Is dropping table possible?
I am changing my application to use hibernate and so far it looks great. Have only one problem, though. I went trough documentation and forums, but maybe I’m searching in a wrong way. I hope you can help me.
Is it possible to DROP TABLE with Hibernate?
(yes, it’s needed, as I map the same class to many tables, and at some point of time some tables become not needed anymore)
Sure, you can use sql query
SQLQuery query = session.createSQLQuery(«drop table xyz»);
Sure, you can use sql query
SQLQuery query = session.createSQLQuery(«drop table xyz»);
Thank, of course manual query works. But is there any db-independent method, which will always work?
Hibernate is not generally geared to performing DDL type operations at runtime. The Hibernate Tools Schema Export can do a drop (of the entire schema!) but I guess this isn’t what you’re after.
Just use the SQL query, I don’t think DROP syntax varies much between databases, the only real downside is that you are hard-coding the table name and can’t use the Hibernate entity name.
Sure, you can use sql query
SQLQuery query = session.createSQLQuery(«drop table xyz»);
Thank, of course manual query works. But is there any db-independent method, which will always work?
mmm, the downside is creating other tables (I believe dropping tables at runtime requires creating other tables then), and mapping your entity to other table (which requires changing SessionFactory’s metadata).
_________________
don’t forget to credit!
Amir Pashazadeh
Payeshgaran MT
پايشگران مديريت طرح
http://www.payeshgaran.co
http://www.payeshgaran.org
http://www.payeshgaran.net
> mmm, the downside is creating other tables (I believe dropping tables at runtime requires creating other tables then), and mapping
your entity to other table (which requires changing SessionFactory’s metadata).
I don’t think he is trying to drop the mapped tables, thats really bad idea.
Hi there!
I have to drop the table SPECTRA in my db. It is the mapping of my Spectra class in package popolamento. Here is my code:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.createQuery(«delete popolamento.Spectra»).executeUpdate();
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
It works and is a db-independent method 🙂
All times are UTC — 5 hours [ DST ]
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.